J'ai quelques problèmes en utilisant has_one, through => model
. Le mieux est de vous montrer mon cas.has_one,: through => modèle VS méthode simple?
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 fonctionne très bien. Je peux faire comment.category
. Le problème est lorsque je crée un nouveau commentaire et que je configure son article, j'ai donc enregistré le commentaire pour que l'association fonctionne. Exemple:
>> 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
de toute façon ne pas mettre en place, construire constructeur et créer méthode. Donc, je veux remplacer mon modèle de commentaire par:
class Comment
belongs_to :article
def category
article.category
end
end
Cela peut-être une bonne idée?
quelqu'un? personne n'a de bonnes opinions? – Hartator