Reputation: 29
I'm trying to choose the right association method.
I have a post model and a category model. I would like a post to belong to many categories and categories to have many models.
The api doc says
if you need to work with the relationship model as its own entity, use has_many :through. Use has_and_belongs_to_many when working with legacy schemas or when you never work directly with the relationship itself."
I don't exactly understand what they mean by the relation model
Things I will be doing include.
My question, Which association will allow me to do above? My preference would be the has_and_belongs_to, as it appears to be a direct association
Thanks
Upvotes: 0
Views: 110
Reputation: 1114
Both will do the job, but the has_and_belongs_to_many is easier to set up and uses less code.
Refer to my answer to this question for some help.
Regards the relationship model, based on your description you do not need it. But just so you know what it is, you need three tables in your database to make the many-to-many relationship work. The middle table is called a join table, you can see one in the answer I refer to above. If you create a model for the join table, that is a relationship model. The advantage is that you can use it to keep information you deem important to the relationship. The disadvantage is the extra complexity (sometimes worth it) and you should then use the more verbose has_many :through approach.
Upvotes: 1