instance method
insert
Ruby on Rails edge
Signature
insert(arel_or_sql, name = nil, pk = nil, id_value = nil, sequence_name = nil, binds = [], returning: nil)
Executes an INSERT query and returns the new record’s ID.
Some adapters support the returning keyword argument, which controls what the method returns: nil (default) returns the id via last_inserted_id; a column name returns that column as a single value; an array of column names returns an Array of column values.
Parameters
-
arel_or_sqlreq -
nameopt = nil -
pkopt = nil -
id_valueopt = nil -
sequence_nameopt = nil -
bindsopt = [] -
returningkey = nil
Source
# File activerecord/lib/active_record/connection_adapters/abstract/database_statements.rb, line 250
def insert(arel_or_sql, name = nil, pk = nil, id_value = nil, sequence_name = nil, binds = [], returning: nil)
unless pk.nil?
ActiveRecord.deprecator.warn(<<~MSG.squish)
Passing `pk` as a positional argument to `insert` is deprecated
and will be removed in Rails 9.0. Pass `returning:` instead —
`insert(arel, name, "id")` becomes `insert(arel, name, returning: "id")`.
MSG
end
unless id_value.nil?
ActiveRecord.deprecator.warn(<<~MSG.squish)
Passing `id_value` as a positional argument to `insert` is
deprecated and will be removed in Rails 9.0. `id_value` was
returned when the database couldn't compute the last inserted id;
callers that pass it already know the value and can use it
directly rather than reading it back from `insert`.
MSG
end
unless sequence_name.nil?
ActiveRecord.deprecator.warn(<<~MSG.squish)
Passing `sequence_name` as a positional argument to `insert` is
deprecated and will be removed in Rails 9.0. It was only used by
PostgreSQL's `use_insert_returning?` currval fallback, which is
deprecated on its own — drop the argument once the
`insert_returning` option is removed.
MSG
end
if binds.any?
ActiveRecord.deprecator.warn(<<~MSG.squish)
Passing `binds` as a positional argument to `insert` is
deprecated and will be removed in Rails 9.0. Use
`Arel.sql(sql_with_placeholders, *binds)` to carry bind values
inside the arel node instead —
`insert(sql, name, nil, nil, nil, binds)` becomes
`insert(Arel.sql(sql, *binds), name)`.
MSG
end
# The `pk` positional argument is really the RETURNING column name.
# Translate it to `returning:` — including the legacy `false` sentinel
# meaning "no primary key / skip RETURNING".
if pk == false
returning ||= []
elsif pk
returning ||= pk
end
intent = QueryIntent.new(adapter: self, arel: arel_or_sql, name: name, binds: binds)
value = _exec_insert(intent, sequence_name, returning: returning)
case returning
when nil
id_value || last_inserted_id(value)
when Array
returning_column_values(value)
else
returning_column_values(value)&.first
end
end
Defined in activerecord/lib/active_record/connection_adapters/abstract/database_statements.rb line 250
· View on GitHub
· Improve this page
· Find usages on GitHub
Defined in ActiveRecord::ConnectionAdapters::DatabaseStatements