Read more

Rails: Migration helper for inserting records without using models

Dominik Schöler
November 27, 2017Software engineer at makandra GmbH

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

Illustration online protection

Rails Long Term Support

Rails LTS provides security patches for old versions of Ruby on Rails (2.3, 3.2, 4.2 and 5.2)

  • Prevents you from data breaches and liability risks
  • Upgrade at your own pace
  • Works with modern Rubies
Read more Show archive.org snapshot

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.

Posted by Dominik Schöler to makandra dev (2017-11-27 10:39)