user2079913
user2079913

Reputation: 23

Ruby on Rails: remembering state and RESTfulness

I am new to Ruby and Rails.

I made a simple application where the index page diaplays a Cars table with columns for make, model, and type (sportscar, SUV, luxury).

I have made it so I can click a column header and sort by that column

I also added a form above the table with a checkbox for each car type where the user can check/uncheck the boxes and click 'submit' and the table will only show cars with the types that were checked.

What I want to be able to do is sort by some column, and then check some boxes/click submit and show the result with the list still sorted AND also filtered.

Right now, I can either sort or filter, but if I do one action my application forgets about the previous action.

What is the RESTful way to do this?

Should I keep the 'settings' in the session hash, and construct a URI from that every time the user makes a new HTTP request?

Upvotes: 2

Views: 574

Answers (2)

rickyrickyrice
rickyrickyrice

Reputation: 577

What's wrong with including sort/filter parameters in the request URI? For example, when you submit the filter form for make of "honda", the uri will be something like /cars?filter[make]=honda. If you also include sort options, the uri could be /cars?filter[make]=honda&sort_by=make.

Inside your controller, you could access these through the params hash:

class CarsController < ApplicationController
  def index
    @filter = params[:filter]  || {}
    @order  = params[:sort_by] || "created_at"

    @cars = Car.where(@filter).order(@order)
  end
end

You can generate these uri's by including the parameters in path helpers in your views:

link_to "Only show hondas", cars_path(:sort_by => @order, :filter => {:make => "honda"})
link_to "Sort by year",     cars_path(:sort_by => :year,  :filter => @filter)

This way, @filter and @order will be "persisted" between requests unless you explicitly change them. (These links are not DRY... you should generate them dynamically).

Upvotes: 1

Austin Mullins
Austin Mullins

Reputation: 7427

Any data kept in the session hash is available as long as the user is logged in. It doesn't matter what the current URI is. You would only need to hack the URI if you wanted to use the params hash.

Therefore, you should do something like session[:sortBy] = :make whenever the sort action is selected. Then, wherever you currently access params[:sortBy] in your controller, pull session[:sortBy] instead.

I'm of course making guesses as to what your symbols look like. Allowing us to see some of your own code would help.

Upvotes: 0

Related Questions