Posts

Showing posts from July, 2016

How to use ActiveRecord has_and_belongs_to_many (HABTM) association in Rails

When building an application in Rails, often when we need to create relationship between objects, we'll try look for the correct association that we can use based on our own use case. One of the association is  has_and_belongs_to_many , a.k.a HABTM (yep, that acronym exists!). While many articles talks about why one should never use HABTM in place of the has_many..., but I think there's a place for HABTM, in my case, I intend to keep my application small and simple. Let's assume I have a 2 models, " Programmer " and " Project ", a programmer can work on many projects, and a project can have many programmers (obviously right?). To do this in Rails, I took the following steps. Generate the migration file rails g migration CreateJoinTableProgrammerProject programmer project This would generate a migration file like the following: class CreateJoinTableProgrammerProject < ActiveRecord :: Migration def change create_join_table : pro