0

assume you have a case like this

class Artist < ActiveRecord::Base
  has_many :albums
  belongs_to :record_label

  def albums
    return 5
  end
end

Is it possible to access the albums relationship without using the Artist#albums, since it has been overridden?

This can happen with mixins or other random cases, it is mostly helpful for tests. Then you can say Artist#albums is actually a relationship to albums

4

2 回答 2

1

使用association,并检索其范围:

a = Artist.first
a.association(:albums).scoped

请注意,association它没有记录,它返回的对象 ( ActiveRecord::Associations::Association) 也没有记录,这意味着scoped也没有记录。

于 2012-07-14T22:13:57.693 回答
0

请问-为什么需要覆盖#albums?这样做的缺点是违反了最小惊喜原则——每个人都希望#albums归还艺术家的专辑。

否则,我会简单地通过Album.where(artist_id: artist.id).

于 2012-07-14T19:02:35.563 回答