在 Rails 中,如何在使用嵌套路由时可靠地查找特定参数?

In Rails, how can I reliably look for a specific parameter when using nested routes?

假设以下路线:

  resources :products do
    resources :images
  end

这将创建以下路由:

          product_images GET    /products/:product_id/images(.:format)                                   images#index
                         POST   /products/:product_id/images(.:format)                                   images#create
       new_product_image GET    /products/:product_id/images/new(.:format)                               images#new
      edit_product_image GET    /products/:product_id/images/:id/edit(.:format)                          images#edit
           product_image GET    /products/:product_id/images/:id(.:format)                               images#show
                         PATCH  /products/:product_id/images/:id(.:format)                               images#update
                         PUT    /products/:product_id/images/:id(.:format)                               images#update
                         DELETE /products/:product_id/images/:id(.:format)                               images#destroy
                products GET    /products(.:format)                                                      products#index
                         POST   /products(.:format)                                                      products#create
             new_product GET    /products/new(.:format)                                                  products#new
            edit_product GET    /products/:id/edit(.:format)                                             products#edit
                 product GET    /products/:id(.:format)                                                  products#show
                         PATCH  /products/:id(.:format)                                                  products#update
                         PUT    /products/:id(.:format)                                                  products#update
                         DELETE /products/:id(.:format)                                                  products#destroy

现在假设我有一个 ProductController 和一个 ProductImageController,它们都继承自 ApplicationController。在 ApplicationController 中,我希望能够有一个名为 active_product 的 属性 自动设置为相关产品。类似于以下内容:

def active_product
  @product = Product.find(params[:id])
end

这里的问题是参数有时被称为:id,有时被称为:product_id。是否有更好的模式能够提取产品 ID 的值?

当然可以,做一下怎么样

def active_product
  @product = Product.find params[:product_id] || params[:id]
end