我有一些問題使用has_one, through => model
。最好的是向你展示我的情況。has_one,:through => model VS簡單方法?
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
聽起來不錯?
人?沒有人有好的意見? – Hartator 2011-05-21 16:58:32