Reputation: 8585
I'm looping through a table to get some values, and then I'm trying to loop another table to get more items:
My Business table looks like this
id name
1 Business 1
2 Business 2
Business Photo table:
id default_pic business_id
1 blahblah.jpg 1
So if I'm trying to loop:
<% @b.each do |b| %>
<%= b.name %>
<%= b.business_photos.default_pic %>
<% end %>
I get undefined method defaul_pic?
I believe because there's no more record after the second loop when its getting Business 2
. Whats the rails way to check record association so I don't get this error?
This is how my models look:
class Business < ActiveRecord::Base
has_many :business_photos
end
class BusinessPhoto < ActiveRecord::Base
belongs_to :business
end
Upvotes: 0
Views: 110
Reputation: 76774
<%= b.business_photos.default_pic if defined?(b.business_photos.default_pic) %>
This is a conditional if statement we use each time we want to include a variable & are unsure of whether it's set. I've been looking for something which can prevent the error from showing through a .each (would take out so much logic from views), but I am yet to find one
Upvotes: 1