使用t.references
和执行SQL
命令创建products
和category
表之间的外键关系,是否有区别?换句话说,做同样的事情有两种不同的方式,还是我在这里错过了什么?Rails中外键约束和引用之间的区别
class ExampleMigration < ActiveRecord::Migration
def up
create_table :products do |t|
t.references :category
end
#add a foreign key
execute <<-SQL
ALTER TABLE products
ADD CONSTRAINT fk_products_categories
FOREIGN KEY (category_id)
REFERENCES categories(id)
SQL
add_column :users, :home_page_url, :string
rename_column :users, :email, :email_address
end
def down
rename_column :users, :email_address, :email
remove_column :users, :home_page_url
execute <<-SQL
ALTER TABLE products
DROP FOREIGN KEY fk_products_categories
SQL
drop_table :products
end
end
Rails 4.2现在支持支持它们的适配器的外键约束:http://edgeguides.rubyonrails.org/4_2_release_notes.html#foreign-key-support – 2015-01-11 00:04:56