Generating a model with many to many in Ruby on Rails

前端 未结 3 1885
深忆病人
深忆病人 2021-02-07 12:31

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 de

3条回答
  •  渐次进展
    2021-02-07 12:58

    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.

提交回复
热议问题