【问题标题】:has_one, :through => model VS simple method?has_one, :through => 模型VS简单方法?
【发布时间】:2011-05-20 09:58:55
【问题描述】:

我在使用 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 无论如何不要设置,构建构造函数和创建方法。所以,我想用以下方式替换我的评论模型:

class Comment
  belongs_to :article
  def category
    article.category
  end
end

听起来不错?

【问题讨论】:

  • 有人吗?没有人有好的意见吗?

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


【解决方案1】:

你的想法没有错。我看不出在很多情况下 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

【讨论】:

  • 更多信息alias_method_chain可以找到here
  • 我觉得这就是 Rails 默认应该做的事情……与其总是查询数据库,不如遍历内存中的对象!
【解决方案2】:

尝试像这样在您的 Category 类中进行更改:

class Category
  has_many :articles
  has_many :comments, :through => :articles
end

【讨论】:

  • 对不起,在stakeoverflow上拼错了。不是我的实际应用程序的问题。
猜你喜欢
  • 2011-10-31
  • 1970-01-01
  • 2019-03-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多