TIL: Insert directly into a table with ActiveRecord
Feb 7, 2025
Recently I have been on a path of trying out SQLite as an alternative to the PostgreSQL server I have running for my personal projects.
Part of this is migrating from PostgreSQL to SQLite.
After having dumped my PostgreSQL database as .json
with TablePlus I then need to import it.
Luckily I found out that ActiveRecord::Base.connection
have a #insert_fixture
method that takes a hash and a table name.
ActiveRecord::Base.connection.insert_fixture(my_hash, "some_table_name")
Putting this together in a task looks like this:
# frozen_string_literal: true
require 'csv'
namespace :import do
desc 'Import the database'
task database: :environment do
ApplicationRecord.with_connection do |conn|
conn.disable_referential_integrity do
Dir[Rails.root.join('storage/import/*.json')].each do |file|
table_name = File.basename(file, '.json')
rows = JSON.parse(File.read(file))
puts "Importing #{rows.size} rows into #{table_name}"
rows.each do |row|
conn.insert_fixture(row, table_name)
end
end
end
end
end
end