[英]Rails 4 eager loading has_one and belongs_to
I have a model Vendor with association: 我有一个与供应商关联的模型:
has_one :school, foreign_key: "school_vendor_id"
I have a model School with association: 我有一个具有协会的示范学校:
belongs_to :vendor, foreign_key: "school_vendor_id"
I have done eager loading: 我已经渴望加载:
@vendors = Vendor.includes(:school).where(:business_id=>@business.id)
My problem is in views. 我的问题在于意见。
<% @vendors.each do |v| %><br/>
<%= v.vendor_name %><br/>
**<%= v.school.id %>** //Gives an error
undefined method `id' for nil:NilClass
If I do <%= v.school.inspect %>
, I get the following result 如果我
<%= v.school.inspect %>
,我得到以下结果
#<School id: 1, school_vendor_id: 1.................
I can't figure out how to display the school record. 我不知道如何显示学校成绩。
The problem is that you've got a vendor that doesn't have an associated school. 问题是您所拥有的供应商没有相关学校。
So v.school
returns nil and v.school.id
raises an error for a particular vendor. 因此
v.school
返回nil,而v.school.id
对特定供应商产生错误。
Your v.school.inspect
is returning a school because it's for some other vendor. 您的
v.school.inspect
正在返校,因为它是供其他供应商使用的。
To fix this, use v.school.try(:id) || 'No associated school'
要解决此问题,请使用
v.school.try(:id) || 'No associated school'
v.school.try(:id) || 'No associated school'
in your view. 您认为
v.school.try(:id) || 'No associated school'
。 Then in your view, you'll be able to see which vendors don't have schools. 然后,在您看来,您将能够看到哪些供应商没有学校。
You could also do the following in your Rails Console to see which vendors don't have schools. 您还可以在Rails控制台中执行以下操作,以查看哪些供应商没有学校。
Vendor.where("id NOT IN (?)", School.pluck(:vendor_id))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.