has_and_belongs_to_many

My Rails work is going pretty well. I am making progress and feel like I am learning quite a bit. I must say that the guides on guides.rubyonrails.com are quite excellent. They cover all the necessary details without going overboard and provide an excellent starter tutorial.

nn

My accomplishment for tonight was figuring out how to use the has_and_belongs_to_many model association. This association creates many-to-many relationships between models. For example, a music playlist contains multiple songs, and any single song can belong to multiple playlists. This association

nn

Here is how to create these associations.

nn

1. Generate your models

nn

Or re-use models that you’ve already created.

nn

2. Add the association keyword

nn

Add has_and_belongs_to_many keyword to each of your models, followed by the name of the model to associate to.

nn

3. Create the migration

nn

The join table, which associates the links the ids from the two models, must be created as a migration. Create a migration called CreateXXXYYYJoinTable where XXX is the name of the first model and YYY is the name of the second model. Inside the model, add a create_table block following the template below:

nn

      create_table :xxxs_yyys, id: false do |t|n          t.integer :xxx_idn          t.integer :yyy_idn      endn

nn

Note the pluralized model names in the name of the block.

nn

4. Run the migration

nn

rake:db_migraten

Leave a Reply

Your email address will not be published. Required fields are marked *