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 comment 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 => :articleswould be the obvious better choice (unless eager-loading withComment.all(:include => :category)).A hint on
delegate:A different approach: