has_one,:through =>模型VS简单方法?

时间:2011-05-20 09:58:55

标签: ruby-on-rails ruby ruby-on-rails-3 activerecord model

我在使用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

听起来不错?

2 个答案:

答案 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