开发者

Foreign keys with Rails' ActiveRecord::Migration?

I'm new to Ruby on Rails (I know Ruby just decently though) and looking at the Migration tools, it sounds really awesome. Database schemas can finally (easily) go in source control.

Now my problem with it. When using Postgres as 开发者_开发百科the database, it does not setup foreign keys. I would like the benefits of foreign keys in my schema such as referential integrity. So how do I apply foreign keys with Migrations?


Rails philosophy is that integrity checks is business logic that belongs in the model. Thats why you are seeing what you are seeing in the DB; whatever_id is just an int and not a "real" fk in sight. Its not a mistake, its by design and its a little freaky at first. Generally the only reason that drives people to work with fks in the DB level is when the DB is accessed by more than one app or its a legacy system. There is plenty of discussion and some great links here: Why do Rails migrations define foreign keys in the application but not in the database?


Check this out: http://github.com/matthuhiggins/foreigner

But first make sure you really need them (e.g. referential integrity is something that theoretically shouldn't break as long as your code is OK, and you know about :dependent => :destroy and the difference between user.delete and user.destroy).


There are a number of plugins available (search google) for Rails that will create foreign keys for you when you use a special symbol in your migrations (foreign_key_migrations is one from the Advanced Rails Recipes book). Just be aware that Rails does not play well with this concept especially when you are trying to delete objects (as mentioned by glebm).


I just came across this post. Maybe someone will find it useful. That's how the constraints are created:

http://guides.rubyonrails.org/migrations.html#using-reversible

class ExampleMigration < ActiveRecord::Migration
def change
create_table :products do |t|
  t.references :category
end

reversible do |dir|
  dir.up do
    #add a foreign key
    execute <<-SQL
      ALTER TABLE products
        ADD CONSTRAINT fk_products_categories
        FOREIGN KEY (category_id)
        REFERENCES categories(id)
    SQL
  end
  dir.down do
    execute <<-SQL
      ALTER TABLE products
        DROP FOREIGN KEY fk_products_categories
    SQL
  end
end

add_column :users, :home_page_url, :string
rename_column :users, :email, :email_address
end
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜