ruby-on-rails - has_one,:through => model VS simple method?

标签 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

一切正常。我可以做 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/

相关文章:

ruby-on-rails - PostgreSQL:在 Rails 迁移中使用 add_column "after"选项

ruby-on-rails - rspec 没有说预期的 : 15. 35,使用 == 得到 : 15. 35,这对我来说没有意义?

ruby - 安装 Ruby 后 MAC OS X 上的事件开发者路径无效

ruby-on-rails - rspec 如何与 Rails 3 一起进行集成测试?

ruby-on-rails - RoR : undefined method `http_basic_authenticate_with'

ruby-on-rails - 使用 map 方法格式化 JSON 输出 - Rails 3

ruby-on-rails - Rails RoutingError(没有路由匹配 [OPTIONS]

ruby-on-rails - 使用 ruby​​ 将字符串转换为哈希

ruby-on-rails - 在使用Rails 3.1进行测试期间禁用终端中的SQL登录? (RSPEC/ cucumber )

mysql - Rails 调用同一个表中的不同字段