Dr.Gonzo
Dr.Gonzo

Reputation: 107

Populate a table in rails 5 using an array

I have a migration in my rails 5 app and I am trying to populate a column with a list of items.

Basically I have a table that breaks down loans by sector.. I am trying to populate the table through the migration file but its not populating it.

Heres is my migration file:

class CreateLoanSectors < ActiveRecord::Migration[5.0]
  def change
    create_table :loan_sectors do |t|
      t.string :name

      t.timestamps

    loan_sector = ['Agriculture/Farming',         'Bars/Public Houses',     'B&B’s'    ,     'Beauty',      'Bio Pharma Engineering',
                    'Cafes',    'Car Sales Industry',     'Construction - Commercial' ,     'Construction - Residential',
                    'Consultancy',   'Distribution Services',    'Education',      'Engineering',       'Entertainment',
                    'Environmental and CleanTech Products and Services',     'Financial Services' ,   'Garages—Car Repair etc.',
                    'Health',      'Hotels',    'Legal services',    'Marketing Services',    'Media Services',    'Motor Industry',
                    'Manufacturing' ,     'Pharmaceuticals',      'Recruitment Services' ,      'Restaurants',        'Retail Services',
                    'Telecoms Industry',   'Tourism',   'Transport - Import',         'Transport - Export',
                    'Transport - Internal',    'Wholesale'].each do |name|

      LoanSector.create(name: name)


      end
    end
  end

  def down
    drop_table :loan_sectors
  end
end

Error:

== 20180802115704 CreateLoanSectors: migrating ================================
-- create_table(:loan_sectors)
rails aborted!
StandardError: An error has occurred, all later migrations canceled:

Mysql2::Error: Table 'flender_development.loan_sectors' doesn't exist: SHOW FULL FIELDS FROM `loan_sectors`

Upvotes: 0

Views: 245

Answers (1)

Stan Mazhara
Stan Mazhara

Reputation: 826

The error is ActiveModel::UnknownAttributeError: unknown attribute 'name' for LoanSector most likely. This is because you just added name attribute to your model, but it has not been reloaded and the ActiveModel does not know of its existence. Do LoanSector.reset_column_information right after you create_table.

Couple more things:

  1. Move you loop inside change method
  2. And you don't really need down method in this case. ActiveRecord::Migration is smart enough to know how to down.

Upvotes: 1

Related Questions