1

为了使用机场名称播种我的数据库,我使用application.yml来定义机场集合:

AIRPORTS:
  - name: "Charles de Gaulle"
    city: "Paris"
    country: "France"
  - name: "Orly"
    city: "Paris"
    country: "France"

使用 Rails 命令(rails c)进行测试,我有:

2.0.0-p247 :001 > ENV['AIRPORTS']
 => "[{\"name\"=>\"Charles de Gaulle\", \"city\"=>\"Paris\", \"country\"=>\"France\"}, {\"name\"=>\"Orly\", \"city\"=>\"Paris\", \"country\"=>\"France\"}]"

这是一个字符串!然后,在输入以下内容时,出现错误:

2.0.0-p247 :002 > YAML.load(ENV['AIRPORTS'])
Psych::SyntaxError: (<unknown>): did not find expected ',' or '}' while parsing a flow mapping at line 1 column 2
from /Users/Hassen/.rvm/rubies/ruby-2.0.0-p247/lib/ruby/2.0.0/psych.rb:205:in `parse'
from /Users/Hassen/.rvm/rubies/ruby-2.0.0-p247/lib/ruby/2.0.0/psych.rb:205:in `parse_stream'
from /Users/Hassen/.rvm/rubies/ruby-2.0.0-p247/lib/ruby/2.0.0/psych.rb:153:in `parse'
from /Users/Hassen/.rvm/rubies/ruby-2.0.0-p247/lib/ruby/2.0.0/psych.rb:129:in `load'
from (irb):2
from /Users/Hassen/.rvm/gems/ruby-2.0.0-p247/gems/railties-3.2.13/lib/rails/commands/console.rb:47:in `start'
from /Users/Hassen/.rvm/gems/ruby-2.0.0-p247/gems/railties-3.2.13/lib/rails/commands/console.rb:8:in `start'
from /Users/Hassen/.rvm/gems/ruby-2.0.0-p247/gems/railties-3.2.13/lib/rails/commands.rb:41:in `<top (required)>'
from script/rails:6:in `require'
from script/rails:6:in `<main>'

我期望(我想要的)是拥有一个对象数组,因此我可以使用以下代码为我的数据库播种:

YAML.load(ENV['AIRPORTS']).each do |airport|
    AirPort.create airport
    puts 'airport created: ' << airport.name
end

谢谢,

4

1 回答 1

1

使用 figarogem这可以解决问题:

(eval ENV["AIRPORTS"]).each do |params|
  Airport.create! params
  puts "Airport created: #{params["name"]}"

我通常使用一个简单的初始化程序load_config.rb,例如:

YAML.load_file(Rails.root.join('config', 'application.yml'))['AIRPORTS'].each |params|
  Airport.create! params
  puts "Airport created #{params['name']}"
end
于 2013-09-01T11:23:41.447 回答