Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

rails member routes

I'm creating a route that should have a url of something like http://mysite/cars/1/similar/, which would get all cars similar to a car with the specified id (in this case 1)

I've seen that you can create rails member routes in the routes.rb file with the syntax

resources :cars do
  member do
    get :similar
  end
end

I can also do something like

match 'cars/:id/similar' => 'cars#similar', :via => "get

What is the difference between these two syntaxes

like image 554
Jeff Storey Avatar asked Dec 07 '22 12:12

Jeff Storey


2 Answers

The two methods are not equivalent.

The first method produces a similar_car helper method. The second method does not.

The helper method is important if you intend to do things like

= link_to "Similar", similar_car_path(@car)

In order to make them equivalent, you would have to provide an :as option:

get "cars/:id/similar" => "cars#similar", :as => "similar_car"
like image 153
meagar Avatar answered Dec 21 '22 22:12

meagar


One is unified within default resource route declarations, IMO easier to find. The other isn't, which could lead to typos etc. Not a huge deal, but for RESTful actions, I'd rather use the resourceful mechanism.

You can also use the single-line version, which I prefer for single routes:

resources :cars do
  get :similar, :on => :member
end

Meagar is correct, I forgot that the match form will not create the helper methods.

like image 41
Dave Newton Avatar answered Dec 21 '22 23:12

Dave Newton