Module: AutomaticForeignKey::ActiveRecord::Base::ClassMethods

Defined in:
lib/automatic_foreign_key/active_record/base.rb

Instance Method Summary collapse

Instance Method Details

#references(table_name, column_name, options = {}) ⇒ Object

Determines referenced table and column. Used in migrations.

references('comments', 'post_id') # => ['posts', 'id']

If column_name is parent_id it references to the same table

references('pages', 'parent_id')  # => ['pages', 'id']

If referenced table cannot be determined properly it may be overriden

references('widgets', 'main_page_id', :references => 'pages')) 
# => ['pages', 'id']

Also whole result may be given by hand

references('addresses', 'member_id', :references => ['users', 'uuid'])
# => ['users', 'uuid']


22
23
24
25
26
27
28
29
30
31
32
33
34
# File 'lib/automatic_foreign_key/active_record/base.rb', line 22

def references(table_name, column_name, options = {})
  column_name = column_name.to_s
  if options.has_key?(:references)
    references = options[:references]
    references = [references, :id] unless references.nil? || references.is_a?(Array)
    references
  elsif column_name == 'parent_id'
    [table_name, :id]
  elsif column_name =~ /^(.*)_id$/
    determined_table_name = ActiveRecord::Base.pluralize_table_names ? $1.to_s.pluralize : $1
    [determined_table_name, :id]
  end
end