2012-07-18 27 views
6

使用t.references和执行SQL命令创建productscategory表之间的外键关系,是否有区别?换句话说,做同样的事情有两种不同的方式,还是我在这里错过了什么?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 

回答

0

我在这个页面发现了一些intresting的东西。

http://railsforum.com/viewtopic.php?id=17318

从评论:

Rails不使用外键来执行他的后端任务。这 ,因为一些像sqlite的数据库不允许在其表上的外键。 所以Rails不提供帮助建立一个外键

也有添加外键数据库表中的宝石foreignerWhat creates the FOREIGN KEY constraint in Ruby on Rails 3?

+3

Rails 4.2现在支持支持它们的适配器的外键约束:http://edgeguides.rubyonrails.org/4_2_release_notes.html#foreign-key-support – 2015-01-11 00:04:56

2

它们不是一回事。默认情况下Rails不会强制数据库中的外键。相反,在命令行创建时的引用也创建了一个常规的索引,如:

add_index :products, :category_id 

更新:

的Rails 5现在实际上不完全是一回事。所以,要回答最初的问题:现在,两者都是一样的。

+0

那么Rails中的引用本质上就是foreign_key + index这个外键吗? – geoboy 2017-09-09 01:09:41

+0

@geoboy这实际上已经在更新的版本中发生了变化。 't.references'也设置一个带索引的外键。 http://edgeapi.rubyonrails.org/classes/ActiveRecord/ConnectionAdapters/SchemaStatements.html#method-i-add_reference – 2017-09-12 16:13:10

+0

这就是我的想法。但是,如果我分别设置外键和索引,那么效果相同?或者在'schema.db'文件中(而不是'foreign_key'和'index')具有't.references'是否有优势? – geoboy 2017-09-13 03:01:26