Skip to content

Instantly share code, notes, and snippets.

@jtsaito
Last active August 29, 2015 14:10
Show Gist options
  • Save jtsaito/6d20c9bea528452168a0 to your computer and use it in GitHub Desktop.
Save jtsaito/6d20c9bea528452168a0 to your computer and use it in GitHub Desktop.
Inserting into an ActiveRecord table without instantiating the model

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment