Thursday, September 27, 2012

Rails database migration for new/addition has_many or has_and_belongs_to_many relation

To add a new relation to ModelOne: has_many ModelTwo:
Then, ModelTwo needs a new model_one_id column

To add a new relation to ModelOne: has_many_and_belongs_to Model_Two:
Then, New table model_ones_model_twos [model_one_id, model_two_id]

$ rails generate migration CreateTableModelOnesModelTwos

class CreateTableModelOnesModelTwos < ActionRecord::Migration
  def up
    create_table 'model_ones_model_twos', :id => false do |t|
      t.integer :model_one_id
      t.integer :model_two_id
    end
  end

  def down
    drop_table 'model_ones_model_twos'
  end
end

The :id=>false here is for turning off automatic add primary key column.

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.