Foreigner
Adds limited SQLite support for Matt Higgins Foreigner.
Allows you to do the following in your migration files
t.foreign_key :posts
Which will generate the following SQL:
FOREIGN KEY ("post_id") REFERENCES "posts"(id)
To enforce the constraint use the genfkey tool included with SQLite:
rake db:migrate
sqlite3 db/development.sqlite3
.genfkey --exec
For more info see www.sqlite.org/cvstrac/fileview?f=sqlite/tool/genfkey.README
Installation
Install as a plugin:
ruby script/plugin install git://github.com/dwilkie/foreigner.git
Install as a gem by adding the following to environment.rb:
config.gem "dwilkie-foreigner", :lib => "foreigner"
API
t.foreign_key(options)
foreign_keys(table_name)
Since SQLite does not have complete ALTER TABLE support
you cannot use the following for an SQLite database
add_foreign_key(from_table, to_table, options)
remove_foreign_key(from_table, options)
Example
The most common use of foreign keys is to reference a table that a model belongs to. For example, given the following model:
class Comment < ActiveRecord::Base
belongs_to :post
end
class Post < ActiveRecord::Base
has_many :comments, :dependent => :delete_all
end
You should add a foreign key in your migration:
t.foreign_key :posts
If the column is named article_id instead of post_id, use the :column option:
t.foreign_key(:posts, :column => 'article_id')
schema.rb
Similar to indexes, the foreign keys in your database are automatically dumped to schema.rb. This allows you to use foreign keys without fighting Rails!
Copyright © 2009 David Wilkie, released under the MIT license