关于Rails与下表的关联的基本问题:
关系定义为 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
答案 0 :(得分:1)
用户 jith 指出 - 设置正确且有效。问题是无法找到一个特定的shop_id。
因此,在使用关联时,请确保所有_id都在另一个表中。
谢谢!