Module: RC::ForeignKey

Instance Method Summary collapse

Instance Method Details

#add_foreign_key_constraint(referencing_table, referenced_table, options = {}) ⇒ Object Also known as: add_foreign_key



3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
# File 'lib/rein/constraint/foreign_key.rb', line 3

def add_foreign_key_constraint(referencing_table, referenced_table, options = {})
  referencing_attribute = (options[:referencing] || "#{referenced_table.to_s.singularize}_id").to_sym
  referenced_attribute  = (options[:referenced] || "id").to_sym

  name = (options[:name] || "#{referencing_attribute}_fk").to_sym

  sql = "ALTER TABLE #{referencing_table}".tap do |sql|
    sql << " ADD CONSTRAINT #{name}"
    sql << " FOREIGN KEY (#{referencing_attribute})"
    sql << " REFERENCES #{referenced_table} (#{referenced_attribute})"
    sql << " ON DELETE #{referential_action(options[:on_delete] || :restrict)}"
    sql << " ON UPDATE #{referential_action(options[:on_update] || :restrict)}"
  end

  execute(sql)

  # A foreign key constraint doesn't have an implicit index.
  add_index(referencing_table, referencing_attribute) if options[:add_index] == true
end

#remove_foreign_key_constraint(referencing_table, referenced_table, options = {}) ⇒ Object Also known as: remove_foreign_key



24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
# File 'lib/rein/constraint/foreign_key.rb', line 24

def remove_foreign_key_constraint(referencing_table, referenced_table, options = {})
  referencing_attribute = options[:referencing] || "#{referenced_table.to_s.singularize}_id".to_sym
  referenced_attribute  = "id".to_sym

  name = options[:name] || "#{referencing_attribute}_fk".to_sym

  if is_a_mysql_adapter?
    execute "ALTER TABLE #{referencing_table} DROP FOREIGN KEY #{name}"
  else
    execute "ALTER TABLE #{referencing_table} DROP CONSTRAINT #{name}"
  end

  # A foreign key constraint doesn't have an implicit index.
  remove_index(referencing_table, referencing_attribute) if options[:remove_index] == true
end