Skip to content

Latest commit

 

History

History
56 lines (42 loc) · 2.02 KB

README.rdoc

File metadata and controls

56 lines (42 loc) · 2.02 KB

Fakey - foreign keys for Rails, in a better way

This is fork of the Sava Chankov’s fakey plugin (github.com/sava/fakey) ported to Rails 3.

Example

# Standard usage
create_table :books do |t|
  t.belongs_to :author
end
# => CREATE TABLE "books" ("id" serial primary key, "author_id" integer REFERENCES "authors")

# Table name specified explicitly
create_table :poems do |t|
  t.belongs_to :author, :references => :poets
end
# => CREATE TABLE "poems" ("id" serial primary key, "author_id" integer REFERENCES "poets")

# Column name specified explicitly (if you don't want _id suffix)
create_table :books do |t|
  t.belongs_to :author, :column => :author
end
# => CREATE TABLE "books" ("id" serial primary key, "author" integer REFERENCES "books")

# Non-integer primary key (for those with legacy databases) - this only works in PostgreSQL now!
execute "CREATE TABLE authors( name VARCHAR(255) PRIMARY KEY)"
create_table :books do |t|
  t.belongs_to :author_name, :column => :author_name, :references => :authors, :type => :string
end
# => CREATE TABLE "books" ("id" serial primary key, "author_name" VARCHAR(255) REFERENCES "authors")

# Non-primary key (for those with legacy databases)
create_table :authors do |t|
  t.integer :ssid
end
execute("ALTER TABLE authors ADD UNIQUE(ssid)") # note that add_index doesn't create constraint!
create_table :books do |t|
  t.belongs_to :author_ssid, :column => :author_ssid, :references => :authors, :referenced_column => :ssid
end
# => CREATE TABLE "books" ("id" serial primary key, "author_ssid" integer REFERENCES "authors"(ssid))

# Adding columns to existing - note that you have to use change_table instead of add_column (this works only in PostgreSQL currently)
change_table :atuhors do |t|
  t.belongs_to :author
end

Compatibility

Rails: 3.0.1

Ruby: tested 1.9.2

PostgreSQL 7.0+

Copyright © 2009 Sava Chankov, released under the MIT license. Thanks to Bryan Evans for database introspection query (taken from drysql gem).