Sha256: d80efe1ebdc3e97cbd498c2df1fd9ed2b21341bdc104229b5f84e2f3da486c92

Contents?: true

Size: 1.16 KB

Versions: 1

Compression:

Stored size: 1.16 KB

Contents

module RC
  module ForeignKey
    def add_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

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

      add_index(referencing_table, referencing_attribute) if options[:index] == true

      execute(sql)
    end

    alias_method :add_foreign_key, :add_foreign_key_constraint

  private
    def referential_action(action)
      case action.to_sym
      when :cascade
        "CASCADE"
      when :restrict
        "RESTRICT"
      when :nullify
        "SET NULL"
      when :default
        "SET DEFAULT"
      else
        raise "Unknown referential action '#{action}'"
      end
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
rein-0.5.1 lib/rein/constraint/foreign_key.rb