Question about belongs_to or has_and_belongs_to


#1

i’ve been looking at has_many and belongs_to

I understand it to be the case that if there is a 1—M between A----B then B points to A, and since B points to A, you put the belongs_to in the B class. and the has_many in the A class. So the class/model whose table will have the foreign key, gets the belongs_to line.

However… i’ve noticed that in the case of a M—M relationship,
so, where table A doesn’t point to table B, and table B doesn’t point to table A. But rails will generate a join table to link them. Yet even though both table A and table B don’t have foreign keys to each other, you still put has_and_belongs_to_many line, that goes in the model for A and the model for B. Even though neither has a foreign key to the other.

So what is the rule for when you write …belongs_to ?


#2

Hi @barilo,

The documentation might be helpful: http://guides.rubyonrails.org/association_basics.html

I’m not sure I understand your question, though - use belongs_to if the entries for that model belong to one entry for a different model. For example, many comments might belong to one user. has_and_belongs_to_many might be used to indicate a user that owns a number of groups, but also belongs to groups owned by other users.


#3

Thanks… You say, "use belongs_to if the entries for that model belong to one entry for a different model. For example, many comments might belong to one user. "

That seems like a circular definition to me, but you have helped me understand it…

I was wondering what the situation is regarding …belongs… and foreign keys… (I was thinking there might be some general rule true for 1-M and M-M).

But rather than looking at it like that, I can see though, that belongs means adheres to… it means there’s a …has…many… on the other side. And for a 1-M relationship the belongs_to goes in the model that has one, of the other model. And for a M-M then each model has many of the other, and thus belongs to the other, so in rails one says has_and_belongs_to_many.

It’s not a general answer relating …belongs… to foreign keys, but it makes sense… I was looking for some technical answer like if it has “belongs” in there then a foreign key of the table was elsewhere… but I think perhaps there isn’t a technical answer like that. I guess it’s more just that there’s A)the meaning of belongs and B) the model where you write …belongs… has a pointer to the other one, just as the model where you write has…many, has a pointer to the other one. So it’s rails way of telling it to make a pointer to the other model.