Rails关联 - nil的未定义方法:NilClass

时间:2017-01-21 09:05:37

标签: ruby-on-rails associations

关于Rails与下表的关联的基本问题:

  • 购物:名称,网络
  • 产品:标题,价格,shop_id

关系定义为 has_many belongs_to

型号:

shop.rb

class Shop < ApplicationRecord
    has_many   :products
end

product.rb

class Product < ApplicationRecord
     self.primary_key = "id"
     belongs_to :shop
end

控制器:

shops_controller.rb

  def show
    @shop = Shop.find(params[:id])
 end

products_controller.rb

  def show
    @product = Product.find(params[:id])
  end

商店视图中,我设法引用并显示每个商店的所有商品而不会出现问题:

<%= @shop.name %>
<%= @shop.network %>

  <% @shop.products.each do |product| %>
   <%= product.title %>
  <% end %>

但在产品视图中,我没有设法显示Shop表中的网络信息:

  <%= @product.title %>
  <%= @product.shop.network %>

这会返回以下错误:

undefined method `network' for nil:NilClass

1 个答案:

答案 0 :(得分:1)

用户 jith 指出 - 设置正确且有效。问题是无法找到一个特定的shop_id。

因此,在使用关联时,请确保所有_id都在另一个表中。

谢谢!

相关问题