Thursday, February 07, 2013

Effective use of the Rails has_and_belongs_to_many association

Just a note to myself and others using the Rails has_and_belongs_to_many association:
  • The naming of the association table is by alphabetical convention. For example, a many-to-many relationship between Assemblies and Parts models would result in an association table named assemblies_parts. The migration will look like:
    class CreateAssembliesPartsAssociationTable < ActiveRecord::Migration
        def self.up
            create_table :assemblies_parts, :id => false do |t|
                t.integer :assembly_id, :null => false
                t.integer :part_id, :null => false
            add_foreign_key(:assemblies_parts, :assemblies)
            add_foreign_key(:assemblies_parts, :parts)
        def self.down
            drop_table :assemblies_parts
    Note that I am using the foreigner gem to implement foreign keys in my migrations.
  • Use this association type when you want a direct many-to-many mapping of models without any intervening association model.
  • The model mapping looks like the following:
    class Assembly < ActiveRecord::Base
        has_and_belongs_to_many :parts
    class Part < ActiveRecord::Base
        has_and_belongs_to_many :assemblies
I just got caught by the alphabetically ordering of the association table name. Thought I would write something up about it.

1 comment: