【发布时间】: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