Method: Sequel::Schema::CreateTableGenerator#foreign_key

Defined in:
lib/sequel/database/schema_generator.rb

#foreign_key(name, table = nil, opts = OPTS) ⇒ Object

Add a foreign key in the table that references another table. See #column for available options.

foreign_key(:artist_id) # artist_id INTEGER
foreign_key(:artist_id, :artists) # artist_id INTEGER REFERENCES artists
foreign_key(:artist_id, :artists, key: :id) # artist_id INTEGER REFERENCES artists(id)
foreign_key(:artist_id, :artists, type: String) # artist_id varchar(255) REFERENCES artists(id)

Additional Options:

:foreign_key_constraint_name

The name to give the foreign key constraint

PostgreSQL specific options:

:not_enforced

Whether the foreign key constraint should be marked NOT ENFORCED.

If you want a foreign key constraint without adding a column (usually because it is a composite foreign key), you can provide an array of columns as the first argument. This changes the method to accept constraint options instead of column options. You can provide the :name option to name the constraint.

PostgreSQL specific options:

:not_enforced

Whether the foreign key constraint should be marked NOT ENFORCED.

:period

Use PERIOD to setup a constraint where the final column is a range or multirange column, and the range or multirange is covered by existing ranges in the referenced table (which can be in separate rows).

foreign_key([:artist_name, :artist_location], :artists, name: :artist_fk)
# ADD CONSTRAINT artist_fk FOREIGN KEY (artist_name, artist_location) REFERENCES artists


239
240
241
242
243
244
245
246
247
248
249
250
# File 'lib/sequel/database/schema_generator.rb', line 239

def foreign_key(name, table=nil, opts = OPTS)
  opts = case table
  when Hash
    table.merge(opts)
  when NilClass
    opts
  else
    opts.merge(:table=>table)
  end
  return composite_foreign_key(name, opts) if name.is_a?(Array)
  column(name, Integer, opts)
end