instance method insert

Ruby on Rails 3.0.20

Since v2.2.3 Last seen in v3.0.20

Available in: v2.2.3 v2.3.18 v3.0.20

Signature

insert(sql, name = nil, pk = nil, id_value = nil, sequence_name = nil)

Executes an INSERT query and returns the new record’s ID

Parameters

sql req
name opt = nil
pk opt = nil
id_value opt = nil
sequence_name opt = nil
Source
# File activerecord/lib/active_record/connection_adapters/postgresql_adapter.rb, line 425
      def insert(sql, name = nil, pk = nil, id_value = nil, sequence_name = nil)
        # Extract the table from the insert sql. Yuck.
        table = sql.split(" ", 4)[2].gsub('"', '')

        # Try an insert with 'returning id' if available (PG >= 8.2)
        if supports_insert_with_returning?
          pk, sequence_name = *pk_and_sequence_for(table) unless pk
          if pk
            id = select_value("#{sql} RETURNING #{quote_column_name(pk)}")
            clear_query_cache
            return id
          end
        end

        # Otherwise, insert then grab last_insert_id.
        if insert_id = super
          insert_id
        else
          # If neither pk nor sequence name is given, look them up.
          unless pk || sequence_name
            pk, sequence_name = *pk_and_sequence_for(table)
          end

          # If a pk is given, fallback to default sequence name.
          # Don't fetch last insert id for a table without a pk.
          if pk && sequence_name ||= default_sequence_name(table, pk)
            last_insert_id(table, sequence_name)
          end
        end
      end

Defined in activerecord/lib/active_record/connection_adapters/postgresql_adapter.rb line 425 · View on GitHub · Improve this page · Find usages on GitHub

Defined in ActiveRecord::ConnectionAdapters::PostgreSQLAdapter

Type at least 2 characters to search.

↑↓ navigate · open · esc close