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
歌曲可能没有分配图像,在这种情况下,调用aSong.image应该返回歌曲的专辑图像。访问控制台中的实例按预期工作,但image
中的第一行返回stack level too deep
错误,我无法弄清楚原因。
我的观看代码:
<% @user.songs.each do |s| %>
<div class='GridItem'>
<%= image_tag("#{ s.image.path }", alt: s.image.caption) %>
</div>
<% end %>
答案 0 :(得分:1)
正在发生的事情是,如果设置了图片,您的image
函数会不停地调用自己:
def image
if self.image
return self.image
...
end
当它自己调用足以填满堆栈时会出现错误。