Module: Rein::Constraint::ForeignKey
- Included in:
- ActiveRecord::ConnectionAdapters::Mysql2Adapter, ActiveRecord::ConnectionAdapters::MysqlAdapter, ActiveRecord::ConnectionAdapters::PostgreSQLAdapter
- Defined in:
- lib/rein/constraint/foreign_key.rb
Overview
This module contains methods for defining foreign key constraints.
Instance Method Summary collapse
- #add_foreign_key_constraint(referencing_table, referenced_table, options = {}) ⇒ Object (also: #add_foreign_key)
- #remove_foreign_key_constraint(referencing_table, referenced_table, options = {}) ⇒ Object (also: #remove_foreign_key)
Instance Method Details
#add_foreign_key_constraint(referencing_table, referenced_table, options = {}) ⇒ Object Also known as: add_foreign_key
5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
# File 'lib/rein/constraint/foreign_key.rb', line 5 def add_foreign_key_constraint(referencing_table, referenced_table, = {}) referencing_attribute = ([:referencing] || "#{referenced_table.to_s.singularize}_id").to_sym referenced_attribute = ([:referenced] || "id").to_sym name = [:name] || default_constraint_name(referencing_table, referencing_attribute) sql = "ALTER TABLE #{referencing_table}" sql << " ADD CONSTRAINT #{name}" sql << " FOREIGN KEY (#{referencing_attribute})" sql << " REFERENCES #{referenced_table} (#{referenced_attribute})" sql << " ON DELETE #{referential_action([:on_delete])}" if [:on_delete].present? sql << " ON UPDATE #{referential_action([:on_update])}" if [:on_update].present? execute(sql) # A foreign key constraint doesn't have an implicit index. add_index(referencing_table, referencing_attribute) if [:add_index] == true end |
#remove_foreign_key_constraint(referencing_table, referenced_table, options = {}) ⇒ Object Also known as: remove_foreign_key
25 26 27 28 29 30 31 32 33 34 35 36 37 38 |
# File 'lib/rein/constraint/foreign_key.rb', line 25 def remove_foreign_key_constraint(referencing_table, referenced_table, = {}) referencing_attribute = [:referencing] || "#{referenced_table.to_s.singularize}_id".to_sym name = [:name] || default_constraint_name(referencing_table, referencing_attribute) if 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 [:remove_index] == true end |