Search code examples
mysqlruby-on-railsrubyruby-on-rails-6

Unable to Insert row in an existing table via migrations - Rails 6


I have a table with about 10 values which are used to populate some view in the application. Table is static as in no operation in the app exists to add/modify data in it. I was tasked with adding a row to this table and was exploring how I could do it. (Do not have write access to the table directly so cannot run queries on the sql server).

I was thinking of creating a migration and using Model.create or Model.new command to create the row. Something like:

class AddNewRowToTestTable < ActiveRecord::Migration[6.1]
  def change
    Model_Name.create({:type_id => "a123", :name => "Test Value", :program => "Test Program"})
  end
end

The above would work and it adds the correct timestamps (for created_at and updated_at columns). However, I came across this stackoverflow post: How do I add some inserts in rails migration? where it is stressed that using a model for data modification is a bad practice as models might change over time and to use raw sql instead. So I tried doing this: (Had to add timestamp code as otherwise it would create null values)

class AddNewRowToTestTable < ActiveRecord::Migration[6.1]
  def change
    execute "insert into table_name (type_id, name, program, created_at, updated_at) values ('a123', 'Test Value', 'Test Program', '#{Time.now}', '#{Time.now}')"
  end
end

However, I get the following error when running the migration:

Strong Migrations does not support inspecting what happens inside an execute call, so cannot help you here. Please make really sure that what you're doing is safe before proceeding, then wrap it in a safety_assured { ... } block.

The query works when I run the sql directly in a test db. The created_at and updated_at columns show up null. (Was not sure how to add rails specific timestamps)

insert into table_name (type_id, name, program) values ('a123', 'Test Value', 'Test Program');

Total rails noob here and would appreciate advice on what I might be doing wrong or the right way of doing this.

Use Rails 6 and Ruby 2.7. Do let me know if any additional details are required. Thanks.

P.S: I do not see a seeds.rb file in our codebase, so not sure how to go about that.


Solution

  • It is not good idea to use migrations just to insert / update some tables

    Migrations are used to change database schema

    May be it's better to write rake task with your

    ModelName.create(type_id: "a123", name: "Test Value", program: "Test Program")
    

    or just using console

    If it is part of some basic data that app need, it's better to use seeds