简体   繁体   English

Rails:直接在“资源”块内声明路由与用“成员”块将其封闭之间的区别

[英]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?下面的/animals/:animal_id/info(.:format)/animals/:id/info(.:format)路由之间有什么区别,参数名称除外? 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.首先,如果我们写member块或者直接在resources里面写get路由,都被认为是成员路由。

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] .但是,如果我们直接在resources块内声明get或其他路由,这也会创建相同的member路由,除了resource id值将在params[:animal_id]中可用而不是params[:id]中。 Route helpers will also be renamed from info_animal_url and info_animal_path to animal_info_url and animal_info_path .路线助手也将从info_animal_urlinfo_animal_path重命名为animal_info_urlanimal_info_path I think this is to make difference that request is not coming from the member block.我认为这是为了区分请求不是来自member块。

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如果我们直接在资源中使用on:选项和值:member编写get路由,那么这将被视为与成员块路由相同

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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