Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generating a model with many to many in Ruby on Rails

Is there a way to generate a Rails model with a many to many relationship predefined? I know how to add it to the Active Record after the fact but it would be nice to have it defined in the DB migration and the Active Record model right off the bat.

like image 393
Kevin Avatar asked Mar 16 '11 07:03

Kevin


People also ask

Has many relationship in Ruby on Rails?

Many-to-many is one of the most common relationship in Rails(database). The concept is simple. When both 2 models have has_many association to each other, we say they are many-to-many relationship.

What is the difference between Has_one and Belongs_to?

They essentially do the same thing, the only difference is what side of the relationship you are on. If a User has a Profile , then in the User class you'd have has_one :profile and in the Profile class you'd have belongs_to :user . To determine who "has" the other object, look at where the foreign key is.

What is polymorphic association in Rails?

In Ruby on Rails, a polymorphic association is an Active Record association that can connect a model to multiple other models. For example, we can use a single association to connect the Review model with the Event and Restaurant models, allowing us to connect a review with either an event or a restaurant.


2 Answers

Remember that you do not want an id for the join table, so make sure to add :id => false |t|

create_table assemblies_parts, :id => false do |t|
  t.integer :assembly_id
  t.integer :part_id
end

If you use rails

rails generate model Assemblies_parts assembly:references part:references

you will have two indexes, but what you want is

# Add table index
add_index :assemblies_parts, [:assembly_id, :part_id], :unique => true

UPDATE

  • For Rails 5 use create_join_table instead to create that (id-less) table.
like image 100
Sully Avatar answered Oct 14 '22 10:10

Sully


You can use this reference from the Rails Guides.Here is the link. Also you will need to manually create the join table for those models using a migration.

e.g

    create_table :assemblies_parts, :force => true do |t|
      t.integer :assembly_id
      t.integer :part_id
    end
like image 42
Shiv Avatar answered Oct 14 '22 11:10

Shiv