Reputation:
When we use has_many_and_belongs_to
, another table is also created which contains id of both table. This table automatically generate another column named row_id
but for other tables this column is named id
. Why is that?
Upvotes: 0
Views: 273
Reputation: 76784
When you use has_many_and_belongs_to
, your join table is literally that -- a join table
The design of this association is that it literally just needs to reference the comparable associations (in your two other models), and therefore doesn't need any primary key:
It's all about foreign_keys
and primary_keys
in relational databases. Relational data, by its nature, means that you can access data in other tables which is related. The way Rails (and any other relational system) identifies this data is to use foreign_keys
(row_id
)
If you use has_many :through
, you need to assign a primary_key
(id
), because it has its own model, like so:
This means that you can reference has_many :through
records directly, as well as being able to reference relational data. It's all about primary_keys
and foreign_keys
Upvotes: 1