How to name a route in rails

前端 未结 2 2146
失恋的感觉
失恋的感觉 2021-02-18 21:00

I have some routes looking like this :

match \'hotels/:action(/:id)\', :controller => \'hotel\', :action => /[a-z]+/i, :id => /[0-9]+/i
2条回答
  •  北荒
    北荒 (楼主)
    2021-02-18 21:47

    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.

提交回复
热议问题