Search code examples
ruby-on-railseager-loadingbelongs-tohas-one

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

#<School id: 1, school_vendor_id: 1.................

I can't figure out how to display the school record.


Solution

  • 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.

    Your v.school.inspect is returning a school because it's for some other vendor.

    To fix this, use v.school.try(:id) || 'No associated school' in your view. 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.

    Vendor.where("id NOT IN (?)", School.pluck(:vendor_id))