I have some issues using has_one, through => model
. The best is to show you my case.
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 works fine. I can do comment.category
. The problem is when I create a new 开发者_StackOverflowcomment and set up its article, I have so save the comment to make the association works. Example :
>> 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
anyway do not set up, build constructor and create method. So, I want to replace my comment model by :
class Comment
belongs_to :article
def category
article.category
end
end
Sounds a good idea ?
Nothing wrong with your idea. I can't see many situations in which has_one :category, :through => :articles
would be the obvious better choice (unless eager-loading with Comment.all(:include => :category)
).
A hint on delegate
:
class Comment
belongs_to :article
delegate :category, :to => :article
A different approach:
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
Try to make changes in your Category class like this:
class Category
has_many :articles
has_many :comments, :through => :articles
end
精彩评论