我应该如何将 ID 传递到收集路线中?

Ang*_*gel 1 ruby windows ruby-on-rails

我是 ruby​​ on Rails 的新手。当用户单击特定产品的购买按钮时,它将获取该产品的 id,然后它将重定向到另一个页面,其中将显示该产品的所有详细信息(名称、描述) 、价格、图片等)..

我创建了一个自定义路线,如下所示:

路线

resources :products do // products is my name of the controller
    collection do
        get :details
    end
  end
Run Code Online (Sandbox Code Playgroud)

看法

<%= button_to 'Add to Cart',details_products_path, class: 'btn btn-primary', method: :get %>
Run Code Online (Sandbox Code Playgroud)

控制器

class ProductsController < ApplicationController
  def index
    @products = Product.all()
  end
  def details
    @product = Product.find(params[:id])
  end

end
Run Code Online (Sandbox Code Playgroud)

注意:我还检查了我的耙子路线,它显示的路径

details_products_path   GET /products/details(.:format) products#details
Run Code Online (Sandbox Code Playgroud)

我注意到没有 id(比如 /products/details/:id)

我也尝试过这个

<%= button_to 'Add to Cart',details_products_path(@products), class: 'btn btn-primary', method: :get %> 
Run Code Online (Sandbox Code Playgroud)

但我收到错误

“ActiveRecord::RecordNotFound in ProductsController#details”无法找到带有 'id'= 的产品

def details
  @product = Product.find(params[:id])
end
Run Code Online (Sandbox Code Playgroud)

问题:如何将 ID 传递到位于产品控制器的详细信息方法中

Dee*_*ale 5

如果你需要product_id在url中,你需要将其定义为成员路由而不是集合

resources :products do
  member do
    get :details
  end
end
Run Code Online (Sandbox Code Playgroud)

现在你会得到

 GET /products/:id/details(.:format) products#details
Run Code Online (Sandbox Code Playgroud)

有关更多详细信息,请参阅添加-更多-restful-actions