Rails migration for has_and_belongs_to_many join table

后端 未结 6 1422
花落未央
花落未央 2020-11-29 15:40

How do I do a script/generate migration to create a join table for a has_and_belongs_to_many relationship?

The application runs on Rails 2.

6条回答
  •  遥遥无期
    2020-11-29 16:31

    The top answer shows a composite index that I don't believe will be used to lookup apples from oranges.

    create_table :apples_oranges, :id => false do |t|
      t.references :apple, :null => false
      t.references :orange, :null => false
    end
    
    # Adding the index can massively speed up join tables.
    # This enforces uniqueness and speeds up apple->oranges lookups.
    add_index(:apples_oranges, [:apple_id, :orange_id], :unique => true)
    # This speeds up orange->apple lookups
    add_index(:apples_oranges, :orange_id)
    

    I did find the answer this is based on by 'The Doctor What' useful and the discussion certainly so too.

提交回复
热议问题