Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing parameters to custom RESTful routes in Rails (using :collection)

I am trying to add a custom route to my RESTful routes using the :collection param on map.resources like so:

map.resources :products, :collection => { :tagged => :get }

The tagged action takes in a :tag parameter. I am able to link to the URL route using: tagged_products_path(:tag => tag.name). My issue with this is that the URL that this generates:

/products/tagged?tag=electronic

I would like the tag to be in the URL and not the tag, like so:

/products/tagged/electronic

Of course this can be accomplished by a separate named route, but I'm wondering if I'm missing something and there is a way to do this with the :collection hash.

Thanks in advance for your help

-Damien

like image 371
dwhite Avatar asked Apr 11 '10 02:04

dwhite


3 Answers

Collection routes don't support this - you'll have to use a named route.

map.tagged_products '/products/tagged/:tag', 
  :controller => 'products', :action => 'tagged', :conditions => { :method => :get }
like image 124
Jonathan Julian Avatar answered Sep 22 '22 12:09

Jonathan Julian


Since the answer is for Rails 2, I just wanted to add the Rails 4 version of this.

get '/products/tagged/:tag' => 'products#tagged', as: :tagged_products

This would be used as

tagged_products_path('electronic') #=> "/products/tagged/electronic"
like image 28
jeremywoertink Avatar answered Sep 24 '22 12:09

jeremywoertink


Collection routes do not support this but there is a workaround.

"#{tagged_products_path}?#{{:tag => tag.name}.to_query}}"
like image 44
Matt Fields Avatar answered Sep 22 '22 12:09

Matt Fields