开发者

How to provide has_many through association through 3 models?

开发者 https://www.devze.com 2022-12-10 23:25 出处:网络
I hope someone has already experienced this. Please help me, how can i solve this problem: class Article < ActiveRecord::Base

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

精彩评论

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