-
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 end add_foreign_key(:assemblies_parts, :assemblies) add_foreign_key(:assemblies_parts, :parts) end def self.down drop_table :assemblies_parts end end
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 end
andclass Part < ActiveRecord::Base has_and_belongs_to_many :assemblies end
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:
Labels:
database migrations,
rails
Subscribe to:
Post Comments (Atom)
Fantastic post, Keep sharing.
ReplyDeletevisit our website
Vashikaran Astrologer in Jayanagar
Thanks for providing this information. It's very helpful.
ReplyDeleteVisit Best Astrologer in Rajanna Sircilla
Good astrologycal post,thank you for sharing with community.
ReplyDeleteFor sofa repair work contact thesofastore gives.
Sofa Refurbishing in Ashok Nagar
This is a good article. Thanks for sharing
ReplyDeleteabhiram astrology center. Best indian Astrologer In alberta