class Song < ActiveRecord::Base
has_one :image
belongs_to :album
def image
if self.image
return self.image
elsif self.album
return self.album.image
else
return nil
end
end
# …Other code
end
class Album < ActiveRecord::Base
has_one :image
has_many :songs
# …Other code
end
Songs might not have an image assigned, and in that case calling aSong.image should return the song's album's image. Accessing instances in the console work as expected, but the first line in image
returns a stack level too deep
error, and I can't figure out why.
My view code:
<% @user.songs.each do |s| %>
<div class='GridItem'>
<%= image_tag("#{ s.image.path }", alt: s.image.caption) %>
</div>
<% end %>