1
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 %>
4

1 回答 1

1

发生的事情是,image如果设置了图像,您的函数会不断地调用自己:

def image
    if self.image
        return self.image
    ...
end

当它调用自己足以填满堆栈时,您会收到该错误。

于 2013-06-14T01:57:00.957 回答