has_many:通过显示视图
我想第一次使用has_many:through。我已经成功地使用了has_many并且属于创建cruds,但是has_many:通过我已经地板。我找到的每个教程和示例都展示了如何设置模型和嵌套表单,但没有“显示”视图。我的代码如下:has_many:通过显示视图
combi_item.rb
class CombiItem < ApplicationRecord
has_many :parts
has_many :products, through: :parts
accepts_nested_attributes_for :products,
:allow_destroy => true,
:reject_if => :all_blank
end
product.rb
class Product < ApplicationRecord
has_many :parts
has_many :combi_items, through: :parts
has_attached_file :image,
:styles => { :medium => "300x300>", :thumb => "100x100>" }
validates_attachment_file_name :image, :matches => [/png\Z/, /jpe?g\Z/, /gif\Z/]
accepts_nested_attributes_for :combi_items,
:allow_destroy => true,
:reject_if => :all_blank
end
part.rb
class Part < ApplicationRecord
belongs_to :combi_item
belongs_to :product
end
combi_items_controller.rb
...
def show
@combi_item = CombiItem.find(params[:id])
@products = @combi_item.products
end
...
show.html.erb
...
<% content_tag_for(:ul, @products.each) do |product| %>
<li>Sku:</li>
<li><%= @product.sku %></li>
<% end %>
...
这给了我一个未定义的方法`SKU”的零:NilClass错误
控制台输出
Processing by CombiItemsController#show as HTML
Parameters: {"id"=>"2"}
CombiItem Load (1.6ms) SELECT `combi_items`.* FROM `combi_items` WHERE `combi_items`.`id` = 2 LIMIT 1
CACHE (0.0ms) SELECT `combi_items`.* FROM `combi_items` WHERE `combi_items`.`id` = 2 LIMIT 1 [["id", 2], ["LIMIT", 1]]
Rendering combi_items/show.html.erb within layouts/application
Product Load (0.4ms) SELECT `products`.* FROM `products` INNER JOIN `parts` ON `products`.`id` = `parts`.`product_id` WHERE `parts`.`combi_item_id` = '2'
Rendered combi_items/show.html.erb within layouts/application (5.8ms)
Completed 500 Internal Server Error in 14ms (ActiveRecord: 2.0ms)
ActionView::Template::Error (undefined method `sku' for nil:NilClass):
27:
28: <% content_tag_for(:ul, @products.each) do |product| %>
29: <li>Sku:</li>
30: <li><%= @product.sku %></li>
31: <% end %>
个查询
Product Load (0.3ms) SELECT `products`.* FROM `products` INNER JOIN `parts` ON `products`.`id` = `parts`.`product_id` WHERE `parts`.`combi_item_id` = '2'
回报2行,既包含sku
value.How我这个页面上显示product
结果?”
那里很少有用于content_tag
那里,除非你做了一些特殊的事情,并在评论中提到删除@
。将其更改为。
<% @products.each do |product| %>
<ul>
<li>Sku:</li>
<li><%= product.sku %></li>
</ul>
<% end %>
完美工作。删除'@'解决了错误,并且在去除了'content_tag','ul'和'li'标记后,按照预期呈现。谢谢。 –
很高兴工作,祝你好运 – Iceman
@product.sku
是零,因为@product
不存在,则使用product.sku
相反,没有@
'product.sku'不是'@ product.sku' – Iceman
即停止错误,但不显示数据。它应该显示2条选定的记录。 –