0

我有以下型号:

class Song < ActiveRecord::Base

  belongs_to :albums

end

class Album < ActiveRecord::Base

  belongs_to :artist
  has_many :songs

end

class Artist < ActiveRecord::Base

  belongs_to :user
  has_many :albums

end

我需要定期确定特定歌曲属于哪个用户。在 Song 模型中添加 belongs_to :user 关系还是每次都调用 song.album.artist.user 是更好的形式吗?

4

1 回答 1

1

看来你违反了得墨忒耳法则。考虑使用delegate

class Song < ActiveRecord::Base

  belongs_to :albums
  delegate :user, :to => :album

end

class Album < ActiveRecord::Base

  belongs_to :artist
  has_many :songs
  delegate :user, :to => :artist

end

class Artist < ActiveRecord::Base

  belongs_to :user
  has_many :albums

end

使用此方法,您现在可以调用song.user

这里的另一个好处是,如果模型的结构发生变化(它可能会发生变化),您可以重新定义或重新委托Song#user给其他东西,这样依赖调用的对象song.user就不会中断。

资源

于 2012-10-14T17:50:25.393 回答