简体   繁体   中英

Rails: Difference between declaring a route directly inside the `resources` block vs. enclosing it with a `member` block

What's the difference between the /animals/:animal_id/info(.:format) and /animals/:id/info(.:format) routes in the following, except parameter names? And why are the parameter names different?

config/routes.rb

Rails.application.routes.draw do
  resources :animals do
    get 'info'

    member do
      get 'info'
    end
  end
end

~/myrails>rails routes

       Prefix Verb   URI Pattern                        Controller#Action
  animal_info GET    /animals/:animal_id/info(.:format) animals#info
  info_animal GET    /animals/:id/info(.:format)        animals#info

First of all, if we write the member block or directly write the get routes inside the resources both are considered as member routes.

Its the rails convention to differentiate between both of the routes. If we write the member block it is considered that all the routes declared within that block are declared from the member block explicitly.

resources :animals do
    member do
      get 'info'
    end
end

info_animal GET    /animals/:id/info(.:format)    animals#info

But if we directly declare get or other routes inside the resources block this will also create the same member route except that the resource id value will be available in params[:animal_id] instead of params[:id] . Route helpers will also be renamed from info_animal_url and info_animal_path to animal_info_url and animal_info_path . I think this is to make difference that request is not coming from the member block.

resources :animals do
    get 'info'
end

animal_info GET    /animals/:animal_id/info(.:format)    animals#info

If we write get route with the on: option with value :member inside the resources directly then this will be treated same as the member block route

resources :animals do
    get 'info', on: :member
end

info_animal GET    /animals/:id/info(.:format)    animals#info

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM