[英]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
belongs_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. 但是author.articles[0].address
工作正常。
I hope you give me advice, how can i solve it. 希望您能给我建议,我该如何解决。 Thanks. 谢谢。
AR does not like sourcing a has_many
through a has_one
. AR不喜欢通过has_one
获取has_many
。 But you can easily get all the addresses with this method on Author
: 但是您可以使用Author
上的此方法轻松获取所有地址:
def addresses
articles.map {|article| article.address }
end
This solution also worked well for different relation types. 此解决方案也适用于不同的关系类型。
eg User.registrations.join_table.periods 例如User.registrations.join_table.periods
but you -can't- apply active_record methods on what is mapped. 但是您-无法-在映射的内容上应用active_record方法。
eg user.periods(:order => :date) eg user.periods.model etc.. 例如user.periods(:order =>:date)例如user.periods.model等。
thanks 谢谢
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.