使用数组在Rails 5中填充表格

时间:2018-08-02 15:39:38

标签: ruby ruby-on-rails-5

我在rails 5应用程序中进行了迁移,并且我试图用项目列表填充一列。

基本上,我有一个按部门细分贷款的表。我试图通过迁移文件填充该表,但不填充它。

这是我的迁移文件:

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

错误:

== 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`

1 个答案:

答案 0 :(得分:1)

错误很可能是ActiveModel::UnknownAttributeError: unknown attribute 'name' for LoanSector。这是因为您刚刚向模型添加了name属性,但尚未重新加载它,并且ActiveModel不知道它的存在。 create_table之后立即执行LoanSector.reset_column_information

再加上一些东西:

  1. change方法内循环移动
  2. 在这种情况下,您实际上并不需要down方法。 ActiveRecord::Migration足够聪明,知道如何down