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 UI/UX Design

UI/UX Design by makandra brand

We make sure that your target audience has the best possible experience with your digital product. You get:

  • Design tailored to your audience
  • Proven processes customized to your needs
  • An expert team of experienced designers
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)