How to name a route in rails

前端 未结 2 2147
失恋的感觉
失恋的感觉 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:39

    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.

    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题