我在使用has_one, through => model
时遇到了一些问题。最好的是告诉你我的情况。
class Category
has_many :articles
end
class Article
has_many :comments
belongs_to :category
end
class Comment
belongs_to :article
has_one :category, :through => :articles
end
Everthing工作正常。我可以做comment.category
。问题是当我创建新评论并设置其文章时,我已保存评论以使关联有效。示例:
>> comment = Comment.new
>> comment.article = Article.last
>> comment.category
-> nil
>> comment.article.category
-> the category
>> comment.save
>> comment.category
-> nil
>> comment.reload
>> comment.category
-> the category
has_one, through => model
无论如何都没有设置,构建构造函数和创建方法。所以,我想通过以下方式替换我的评论模型:
class Comment
belongs_to :article
def category
article.category
end
end
听起来不错?
答案 0 :(得分:6)
你的想法没有错。我看不到很多情况has_one :category, :through => :articles
显然是更好的选择(除非用Comment.all(:include => :category)
加载。)
delegate
上的提示:
class Comment
belongs_to :article
delegate :category, :to => :article
另一种方法:
class Comment
belongs_to :article
has_one :category, :through => :article
def category_with_delegation
new_record? ? article.try(:category) : category_without_delegation
end
alias_method_chain :category, :delegation
答案 1 :(得分:2)
尝试在此类别类中进行更改:
class Category
has_many :articles
has_many :comments, :through => :articles
end