开发者

How to define foreign key, index constraints in my migration script

How should I define foreign key, index 开发者_开发技巧constraints in my db migration script for my Rails app in a 2.3.x environment?


ActiveRecord doesn't support adding foreign keys in a database-agnostic way, so you'll need to do this with DB-specific code. Here's an example for MySQL:

class AddForeignKeyToUsers < ActiveRecord::Migration
  def self.up
    execute 'alter table users add constraint user_role foreign key user_role_idx (role_id) references roles (id) on delete set null on update cascade'
  end

  def self.down
    execute 'alter table users drop foreign key user_role'    
  end
end

For indexes, you can use add_index - like so:

add_index(:users, :name)

Edit: Updated answer to clarify that indexes and foreign keys are treated differently.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜