has_many:通过show view

时间:2017-05-03 20:51:13

标签: ruby-on-rails rails-activerecord

我第一次尝试使用has_many:through。我成功地使用了has_many并且属于创建cruds,但是has_many:通过让我感到沮丧。我发现的每个教程和示例都展示了如何设置模型以及可能是嵌套表单,但没有" show"观点。我的代码如下:

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&#39;为nil: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值。如何在此页面上显示product结果?&#34;

2 个答案:

答案 0 :(得分:2)

content_tag几乎没有任何用处,除非您正在做一些特别的事情,并且如评论中所述删除了@。将其更改为。

<% @products.each do |product| %>
  <ul>      
    <li>Sku:</li>
    <li><%= product.sku %></li> 
  </ul>
<% end %>

答案 1 :(得分:0)

@product.sku为零,因为@product不存在,请使用product.sku而不使用@