Module: Foreigner::ConnectionAdapters::TableDefinition::InstanceMethods
- Defined in:
- lib/foreigner/connection_adapters/sqlite3_adapter.rb,
lib/foreigner/connection_adapters/abstract/schema_definitions.rb
Instance Method Summary collapse
-
#foreign_key(to_table, options = {}) ⇒ Object
Defines a foreign key for the table.
-
#references_with_foreign_keys(*args) ⇒ Object
Adds a :foreign_key option to TableDefinition.references.
- #to_sql_with_foreign_keys ⇒ Object
Instance Method Details
#foreign_key(to_table, options = {}) ⇒ Object
Defines a foreign key for the table. to_table
can be a single Symbol, or an Array of Symbols.
Examples
Creating a simple foreign key
t.foreign_key(:people)
Defining the column
t.foreign_key(:people, :column => :sender_id)
Specify cascading foreign key
t.foreign_key(:people, :dependent => :delete)
85 86 87 88 89 90 |
# File 'lib/foreigner/connection_adapters/sqlite3_adapter.rb', line 85 def foreign_key(to_table, = {}) if @base.supports_foreign_keys? to_table = to_table.to_s.pluralize if ActiveRecord::Base.pluralize_table_names foreign_keys << ForeignKey.new(@base, to_table, ) end end |
#references_with_foreign_keys(*args) ⇒ Object
Adds a :foreign_key option to TableDefinition.references. If :foreign_key is true, a foreign key constraint is added to the table. You can also specify a hash, which is passed as foreign key options.
Examples
Add goat_id column and a foreign key to the goats table.
t.references(:goat, :foreign_key => true)
Add goat_id column and a cascading foreign key to the goats table.
t.references(:goat, :foreign_key => {:dependent => :delete})
Note: No foreign key is created if :polymorphic => true is used.
63 64 65 66 67 68 69 70 71 72 73 |
# File 'lib/foreigner/connection_adapters/sqlite3_adapter.rb', line 63 def references_with_foreign_keys(*args) = args. = .delete(:foreign_key) if && ![:polymorphic] = {} if == true args.each { |to_table| foreign_key(to_table, ) } end references_without_foreign_keys(*(args << )) end |
#to_sql_with_foreign_keys ⇒ Object
47 48 49 50 51 |
# File 'lib/foreigner/connection_adapters/abstract/schema_definitions.rb', line 47 def to_sql_with_foreign_keys sql = to_sql_without_foreign_keys sql << ', ' << (foreign_keys * ', ') if foreign_keys.present? sql end |