Har*_*tor 12 ruby activerecord model ruby-on-rails ruby-on-rails-3
我有一些问题使用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
Run Code Online (Sandbox Code Playgroud)
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
Run Code Online (Sandbox Code Playgroud)
has_one, through => model
无论如何不要设置,构建构造函数和创建方法.所以,我想通过以下方式替换我的评论模型:
class Comment
belongs_to :article
def category
article.category
end
end
Run Code Online (Sandbox Code Playgroud)
听起来不错?
你的想法没有错.我看不到很多情况has_one :category, :through => :articles
会是明显更好的选择(除非急于加载Comment.all(:include => :category)
).
提示delegate
:
class Comment
belongs_to :article
delegate :category, :to => :article
Run Code Online (Sandbox Code Playgroud)
一种不同的方法:
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
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
1122 次 |
最近记录: |