Rails: Migration helper for inserting records without using models

Updated . Posted . Visible to the public.

You should avoid using application models in your migrations. But how else could you create records in a migration?

The most basic way is to write plain SQL, but since INSERT statements are no pleasant write for Rubyists, here is a simple wrapper:

Record creation helper for migrations

The helper method below takes a table name and a hash of attributes, which it inserts into the specified table. Copy it over to your migration and profit!

  private

  def insert_record(table, **attributes)
    attributes.merge!(
      updated_at: Time.now,
      created_at: Time.now,
    )

    insert <<-SQL.squish
      INSERT INTO #{table}
      (#{attributes.keys.join ', '})
      VALUES
      (#{attributes.values.map(&connection.method(:quote)).join ', '})
    SQL
  end

Usage example:

insert_record 'users', name: 'joe', age: 15

Also see Rails: Talking to the database without instantiating ActiveRecord objects.

Dominik Schöler
Last edit
Michael Leimstädtner
License
Source code in this card is licensed under the MIT License.
Posted by Dominik Schöler to makandra dev (2017-11-27 09:39)