我在使用 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
一切正常。我可以做 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
反正不用设置,build constructor 和create method。所以,我想用以下方式替换我的评论模型:
class Comment
belongs_to :article
def category
article.category
end
end
听起来不错?
最佳答案
你的想法没有错。我看不到很多情况下 has_one :category, :through => :articles
显然是更好的选择(除非使用 Comment.all(:include => 预先加载:类别)
)。
关于委托(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
关于ruby-on-rails - has_one,:through => model VS simple method?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6070281/