Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails has_many :through --> Should I keep a primary key column?

I have 'author' and 'book' tables, joined in a has_many :through table 'author_book'

As far as I can tell, there's no purpose to an :id primary key field on the 'author_book' table...but before I commit to that idea, I just wanted to confirm. So, is there any reason for keeping the 'id' column on a has_many :through table?

Thanks in advance...

like image 953
PlankTon Avatar asked Dec 24 '12 23:12

PlankTon


People also ask

What is Activerecord in Ruby on Rails?

Active Record is the M in MVC - the model - which is the layer of the system responsible for representing business data and logic. Active Record facilitates the creation and use of business objects whose data requires persistent storage to a database.

What is Has_and_belongs_to_many?

Rails offers two different ways to declare a many-to-many relationship between models. The first way is to use has_and_belongs_to_many, which allows you to make the association directly: The second way to declare a many-to-many relationship is to use has_many :through.

What is associations in Rails?

In Rails, an association is a connection between two Active Record models. Why do we need associations between models? Because they make common operations simpler and easier in your code. For example, consider a simple Rails application that includes a model for authors and a model for books.


3 Answers

Keep it. Later on youll find the unique identifier pay off in ways that aren't obvious initially.
Unlike other agile development principles, it's better to get data quality items like this addressed up front.

like image 95
Michael Durrant Avatar answered Nov 15 '22 19:11

Michael Durrant


If you ever have something unique to the author-book relationship, you'll need the id to set it in this table via an AuthorBook model. It doesn't sound like a likely scenario in this case, and you can add it later if you need to.

like image 31
PinnyM Avatar answered Nov 15 '22 18:11

PinnyM


If it's has_many through that means that author_book is a active record model, so please leave id for it. But if you'll use has_and_belongs_to_many connecting table doesn't need id http://apidock.com/rails/ActiveRecord/Associations/ClassMethods/has_and_belongs_to_many

like image 26
Anatoliy Kukul Avatar answered Nov 15 '22 18:11

Anatoliy Kukul