Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to name a route in rails

Tags:

I have some routes looking like this :

match 'hotels/:action(/:id)', :controller => 'hotel', :action => /[a-z]+/i, :id => /[0-9]+/i

And i want to use something like hotels_dislike_path somewhere in my code which refers to /hotels/dislike

How can i do that?

like image 910
Sebastien Avatar asked Oct 27 '11 08:10

Sebastien


People also ask

Which method is used to named routes?

When you name a route, a new method gets defined for use in your controllers and views; the method is called name_url (with name being the name you gave the route), and calling the method, with appropriate arguments, results in a URL being generated for the route.

How do you define a route in Ruby?

We have to define the routes for those actions which are defined as methods in the BookController class. Open routes. rb file in library/config/ directory and edit it with the following content. The routes.


2 Answers

From the routing guide:

3.6 Naming Routes

You can specify a name for any route using the :as option.

match 'exit' => 'sessions#destroy', :as => :logout

So, in your case, that would be:

match 'hotels/:action(/:id)', :controller => 'hotel', :action => /[a-z]+/i, :id => /[0-9]+/i
match 'hotels/dislike(/:id)', :controller => 'hotel', :id => /[0-9]+/i, :as => :hotels_dislike
match 'hotels/like(/:id)', :controller => 'hotel', :id => /[0-9]+/i, :as => :hotels_like

I don't think there's a way to do this dynamically (so you have to define one route for each action, basically). However, you can just define a couple of routes (like above) for the most used actions, and just use hotels_path :action => :really_like for more uncommon actions.

like image 73
Felix Avatar answered Oct 14 '22 17:10

Felix


A lot has changed in the world of Rails since 2011 - this is how you would accomplish the same goal in Rails 4.

resources :hotels do
  member do
    post 'dislike'
    post 'like'
  end
end

The resulting routes:

   dislike_hotel POST     /hotels/:id/dislike(.:format)   hotels#dislike
      like_hotel POST     /hotels/:id/like(.:format)      hotels#like
          hotels GET      /hotels(.:format)               hotels#index
                 POST     /hotels(.:format)               hotels#create
       new_hotel GET      /hotels/new(.:format)           hotels#new
      edit_hotel GET      /hotels/:id/edit(.:format)      hotels#edit
           hotel GET      /hotels/:id(.:format)           hotels#show
                 PATCH    /hotels/:id(.:format)           hotels#update
                 PUT      /hotels/:id(.:format)           hotels#update
                 DELETE   /hotels/:id(.:format)           hotels#destro

Notice thats rails prefixes instead of postfixes the action - dislike_hotel_path not hotels_dislike.

like image 32
max Avatar answered Oct 14 '22 17:10

max