开发者

How to provide has_many through association through 3 models?

I hope someone has already experienced this. Please help me, how can i solve this problem:

class Article < ActiveRecord::Base
  belongs_to :author
  be开发者_如何学Clongs_to :publisher
  has_one :address, :through => :publisher
end

class Author < ActiveRecord::Base
  has_many :articles
  has_many :addresses, :through => :articles, :source => :address
end

I try to get "addresses" for "author", and i get this error in console:

ActiveRecord::HasManyThroughSourceAssociationMacroError: Invalid source reflection macro :has_one :through for has_many :addresses, :through => :articles.  Use :source to specify the source reflection.

but author.articles[0].address works fine.

I hope you give me advice, how can i solve it. Thanks.


AR does not like sourcing a has_many through a has_one. But you can easily get all the addresses with this method on Author:

def addresses
  articles.map {|article| article.address }
end


This solution also worked well for different relation types.

e.g. User.registrations.join_table.periods

but you -can't- apply active_record methods on what is mapped.

e.g. user.periods(:order => :date) e.g. user.periods.model etc..

thanks

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜