我希望有人已经体验过这一点。 请帮帮我,我该如何解决这个问题:
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
我尝试为“作者”获取“地址”,我在控制台中收到此错误:
ActiveRecord::HasManyThroughSourceAssociationMacroError: Invalid source reflection macro :has_one :through for has_many :addresses, :through => :articles. Use :source to specify the source reflection.
但是author.articles[0].address
工作正常。
我希望你给我建议,我该如何解决呢。 感谢。
答案 0 :(得分:0)
AR不喜欢通过has_many
采购has_one
。但您可以在Author
上轻松获取此方法的所有地址:
def addresses
articles.map {|article| article.address }
end
答案 1 :(得分:0)
此解决方案也适用于不同的关系类型。
e.g。 User.registrations.join_table.periods
但是你不能 - 在映射的内容上应用active_record方法。
e.g。 user.periods(:order =&gt;:date) 例如user.periods.model等..
感谢