There are several reasons why one would avoid creating records through ActiveRecord::Base
models. One reason is speed for batch inserts, another one is avoiding callbacks or overwritten method calls.
In such cases ActiveRecord::Base#connection.execute
or similary methods can be used. They can be combined with Areal for generating SQL code (or other representations) as follows.
Suppose we have an ActiveRecord
model User
with attributes name
(String) and zipcode
(integer). The following snippet adds a new record.
insert_manager = Arel::InsertManager.new(ActiveRecord::Base)
table = User.arel_table
arel_attributes = [[table[:name], "John Doe"], [table[:zipcode], "55555"]]
insert_manager.insert(arel_attributes)
# => INSERT INTO "users" ("name", "zipcode") VALUES ('John Doe', 5555)
ActiveRecord::Base.connection.execute(insert_manager.to_sql)
The Arel::Table[]
looks up an Arel::Attribute
which contains the attribute's type. This allows Arel to generate the correct interpolation of attribute values in SQL.
References