Foo
Foo

Reputation: 810

How should I make this routing RESTful?

For RESTful purpose, I made my routing just like this:

routes.rb

match 'shops/:sort/:genre/:area', :to => 'shops#index'  

But what if genre was empty? Isn't it going to redirect to example.com/shops/newest_first//california?

How can I solve this kind of routing and parameters problem? Can anyone show me good example?

view

<%= form_tag shops_path, :method => :get do %>
    <%= select_tag :sort, options_from_collection_for_select(Sort.all, 'id', 'name', params[:sort]), :prompt => "Newest first" %>
    <%= select_tag :genre, options_from_collection_for_select(Genre.all, 'id', 'name', params[:genre]), :prompt => "all" %>
    <%= select_tag :area, options_from_collection_for_select(Area.all, 'id', 'name', params[:area]), :prompt => "all" %>
<% end %>

Another View

Upvotes: 0

Views: 78

Answers (1)

Erez Rabih
Erez Rabih

Reputation: 15788

While restful routing is the most intuitive and conventional, it does not always fit our needs.

In your case I'd suggest using query parameters instead of a strict restful route.

example.com/shops will receive 3 query parameters: sort, genre and area, so a URL may look like example.com/shops?area=california&sort=newest_first

The in the index action of you controller you can query for the existence of these parameters in the following manner:

def index
  if !params[:sort].blank?
    @shops = @shops.sort(params[:sort])
  end
  if !params[:area].blank?
    @shops = @shops.where(:area => params[:area])
  end
  .
  .
  .
end

This way you are well protected against missing parameters in your controller, but still you are able to supply whatever data the user requests.

On a side note: be sure to check that the params hash you're using contains only values you are willing to accept.

Upvotes: 2

Related Questions