我想第一次使用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
結果?」
'product.sku'不是'@ product.sku' – Iceman
即停止錯誤,但不顯示數據。它應該顯示2條選定的記錄。 –