Method: Sequel::Database#create_join_table
- Defined in:
- lib/sequel/database/schema_methods.rb
#create_join_table(hash, options = OPTS) ⇒ Object
Create a join table using a hash of foreign keys to referenced table names. Example:
create_join_table(cat_id: :cats, dog_id: :dogs)
# CREATE TABLE cats_dogs (
# cat_id integer NOT NULL REFERENCES cats,
# dog_id integer NOT NULL REFERENCES dogs,
# PRIMARY KEY (cat_id, dog_id)
# )
# CREATE INDEX cats_dogs_dog_id_cat_id_index ON cats_dogs(dog_id, cat_id)
The primary key and index are used so that almost all operations on the table can benefit from one of the two indexes, and the primary key ensures that entries in the table are unique, which is the typical desire for a join table.
The default table name this will create is the sorted version of the two hash values, joined by an underscore. So the following two method calls create the same table:
create_join_table(cat_id: :cats, dog_id: :dogs) # cats_dogs
create_join_table(dog_id: :dogs, cat_id: :cats) # cats_dogs
You can provide column options by making the values in the hash be option hashes, so long as the option hashes have a :table entry giving the table referenced:
create_join_table(cat_id: {table: :cats, type: :Bignum}, dog_id: :dogs)
You can provide a second argument which is a table options hash:
create_join_table({cat_id: :cats, dog_id: :dogs}, temp: true)
Some table options are handled specially:
- :index_options
-
The options to pass to the index
- :name
-
The name of the table to create
- :no_index
-
Set to true not to create the second index.
- :no_primary_key
-
Set to true to not create the primary key.
119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 |
# File 'lib/sequel/database/schema_methods.rb', line 119 def create_join_table(hash, =OPTS) keys = hash.keys.sort create_table(join_table_name(hash, ), ) do keys.each do |key| v = hash[key] unless v.is_a?(Hash) v = {:table=>v} end v[:null] = false unless v.has_key?(:null) foreign_key(key, v) end primary_key(keys) unless [:no_primary_key] index(keys.reverse, [:index_options] || OPTS) unless [:no_index] end nil end |