这段 Rails 代码有什么作用?:上 => :成员

dex*_*00x 5 ruby-on-rails

请你解释一下这段代码的作用是什么?

resources :products do
 get :who_bought, :on => :member
end
Run Code Online (Sandbox Code Playgroud)

完整的代码来自《实用编程》一书,但它没有解释为什么我们使用该代码“:on =>:member”

Depot::Application.routes.draw do
  resources :orders



resources :line_items
 post 'line_items/decrease'


resources :carts


get "store/index"

resources :products do
   get :who_bought, :on => :member
end

root :to => 'store#index', :as => 'store'
Run Code Online (Sandbox Code Playgroud)

谢谢

jvn*_*ill 6

通过:on => :member意味着您正在处理数据库中的特定记录,在本例中为产品。所以路由生成的url是

/products/:id/who_bought

这意味着您想要获取 id 为 :id 的产品并处理 who_bought 操作。对应的 ,:on => :collection期望该操作适用于产品列表,因此 url 将如下所示

/products/who_bought

如果您将成员更改为集合。您可以看到该路由不需要传递 :id,因为它不希望您处理单个记录。