Rails: Migration helper for inserting records without using models

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 Over 6 years ago