gpt4 book ai didi

ruby-on-rails - 在 Rails 中按类别显示产品

转载 作者:行者123 更新时间:2023-12-04 18:16:37 25 4
gpt4 key购买 nike

Rails 初学者在这里。我想显示属于特定类别的所有产品的列表。我想保持简单,所以每个产品只有一个类别。当我显示类别时,产品在那里,但它们出现在一个数组中,如下所示:

Name: Soldering

Category ID: 2

Products: [#< Product id: 5, title: "Hacksaw", description: "Finetooth Hacksaw", image_url: >>"hacksaw.jpg", price: #, created_at: "2012-07-14 >>22:34:07", updated_at: "2012-07-17 22:18:14", category_id: 2, category_name: nil>, #< Product id:8, >>title: "Torch", description: "Welding Torch", image_url: "torch.jpg", price: >>#, created_at: "2012-07-15 08:40:05", >>updated_at: "2012-07-15 08:40:05", category_id: 2, category_name: nil>]



这是类别/show.html.erb:
<p>
<b>Products:</b>
<%= @category.products %></p>
</p>

和类别 Controller :
def show
@category = Category.find(params[:id])

respond_to do |format|
format.html # show.html.erb
format.json { render json: @category }
end
end

我想要做的只是显示产品名称列表,但是当我在 show.html.erb 中尝试这个时:
<p>
<b>Products:</b>
<%= @category.product.name %></p>
</p>

...我收到以下错误:

undefined method `product' for #< Category:0x007ff03cd59e98>



我不知道出了什么问题。

最佳答案

您需要遍历您的 @category.products . @category.products会给你所有Product属于 @category 的型号.
@category ( Category ,它有 Product 的集合)不会响应 product - 它不知道那是什么。它只知道它有一堆 Product s。

<% @category.products.each do |product| %>
<p>
<b>Product:</b>
<%= product.name %>
</p>
<% end %>

关于ruby-on-rails - 在 Rails 中按类别显示产品,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11550922/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com