user1670773
user1670773

Reputation:

Why has_many_and_belongs_to table id is named rowid

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

Answers (1)

Richard Peck
Richard Peck

Reputation: 76784

When you use has_many_and_belongs_to, your join table is literally that -- a join table


has_and_belongs_to_many

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:

enter image description here

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)


has_many :through

If you use has_many :through, you need to assign a primary_key (id), because it has its own model, like so:

enter image description here

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

Related Questions