【问题标题】:what is the proper syntax for seeding a database with an array?用数组播种数据库的正确语法是什么?
【发布时间】:2013-05-01 19:56:21
【问题描述】:

我是一个 Rails 菜鸟,我正在尝试用一个数组为我的数据库播种,然后用一个循环来填充,将相关代码分配给相关变量。但是,它不起作用。请帮忙。

   Customer.delete_all
    b[0]=[1231215,'Jeremy', 'G', '9177477337',
   'jt@gmail.com', 'Central Ave', 'Rockaway', 'NY', ' 12291', '76 Son Court',
   'ft lauderdale','Florida', '32423', '1', '0', '1', '1', '1', '1', '0', '0', '1',          '0', '9.95', 
  'Honda', '2012', 'Civic', '2.4 Turbo', 'Special', '1J474GFGDHDH8883334D0','fart monkey trap']

   b[1]=[46545465,'Se', 'Wof', '521428788',
   'steven.j.wolfman@gmail.com', '13 NE 17 Street', 'broward', 'FL', ' 32222', '13 NE 17 Street',
   'boca','Florida', '32222', '0', '0', '1', 
   '0', '0', '1', '1', 
   '1', '1', '1', '19.95', 
   'Ford', '2012', 'Taurus', '4.0', 'Faster', '3458GDHD3YU34D0','it smells']

   i=0
   while i<2 do
    Customer.create(
        :uid=>b[i][0],
        :fname=>b[i][1],
        :lname=>b[i][2],
        :devphone=> b[i][3],
        :email=>b[i][4],
        :address=>b[i][5],
        :city=>b[i][6],
        :state=>b[i][7],
        :zip=>b[i][8],
        :baddress=>b[i][9],
        :bcity=>b[i][10],
        :bstate=>b[i][11],
        :bzip=>b[i][12],
        :roadass=>b[i][13],
        :crisisass=>b[i][14],
        :autocrash=>b[i][15],
        :emergencyass=>b[i][16],
        :remotediag=>b[i][17],
        :carfind=>b[i][18],
        :familytrack=>b[i][19],
        :lowbatt=>b[i][20],
        :towalerts=>b[i][21],
        :monthlycost=>b[i][22],
        :Make=>b[i][23],
        :Year=>b[i][24],
        :Model=>b[i][25],
        :Engine=>b[i][26],
        :VehicleSystem=>b[i][27],
        :vinnum=>b[i][28],
        :signupdate=>b[i][29],
        :password=>b[i][30],
        )
    i+=1
    end

这是我在运行 db:seed 时遇到的错误: 耙中止! main:Object 的未定义局部变量或方法“b”

【问题讨论】:

  • 尽管回答了这个问题,但我觉得这不是一种非常 Ruby 式的数据库播种方式。您不只是使用两个单独的create 调用是否有特殊原因?
  • 我已经有一个数组中的数据,我不想重新输入它。

标签: ruby-on-rails ruby rake seeding


【解决方案1】:

在尝试分配值之前,您没有将 b 实例化为 Array。当您调用 b[0] 时,b 仍然是 NilClass

要“按原样”工作,您需要插入

b = []

就在Customer.delete_all下面。

【讨论】:

  • 作为旁注,您也可以使用b = Array.new。或者在将来,如果你正在做数组,你可以只做 b = [whatever, whatever] 最初用一些数据来实例化它。但丹是对的。
  • 谢谢您的回答。我没有意识到我犯了这样一个愚蠢的错误。非常感谢您的宝贵时间。
【解决方案2】:

一个更好的方法是

 b.each |customer_record|
   customer = Customer.create!
   Customer.first.attributes.each_with_index do |column_name, index|
     customer[column_name[0]] = customer_record[index]
   end
   customer.save!
 end

【讨论】:

    最近更新 更多