Rails.application.load_seed 有效,但 rake db:seed 无效
rake 环境和控制台环境有什么区别?
我正在尝试使用带有 Rails 3.1.0 的 csv 文件为 mysql 数据库播种。 使用 ActiveRecord::Fixtures 曾经是小菜一碟。不幸的是,csv 固定装置在 Rails 3.1 中已被贬值。
所以我使用 csv-mapper 0.5.1 在我的配置/初始化程序中编写了 load_fixture.rb 。但是,它不适用于
$ rake db:seed
种子代码运行时没有错误。它只是不加载任何数据。
当我将种子代码复制到 Rails 控制台或 Cucumber 步骤中时,它可以完美运行。它甚至可以在 Rails 控制台中使用
> Rails.application.load_seed
。怎么会发生这种事呢?
load_fixture.rb:
require 'csv-mapper'
include CsvMapper
def load_fixture(file)
fname = File.basename file.chomp(File.extname file)
modelname = fname.camelize.singularize.constantize
results = import(file) do
map_to modelname
after_row lambda{|row, item| item.save! }
start_at_row 1
read_attributes_from_file
end
end
seed.rb(简化)
load_fixture("path-to-csv-file")
What is the difference between rake environment and console environment?
I am trying to seed mysql database using csv file with rails 3.1.0.
It used to be a piece of cake with ActiveRecord::Fixtures. Unfortunately, csv fixture is depreciated in rails 3.1.
So I wrote load_fixture.rb in my config/initializers using csv-mapper 0.5.1. However, it does not work with
$ rake db:seed
The seed code runs without error. It just doesn't load any data.
When I copy the seed code into rails console or cucumber step, it works flawlessly. It even works with
> Rails.application.load_seed
in rails console. How can this happen?
load_fixture.rb:
require 'csv-mapper'
include CsvMapper
def load_fixture(file)
fname = File.basename file.chomp(File.extname file)
modelname = fname.camelize.singularize.constantize
results = import(file) do
map_to modelname
after_row lambda{|row, item| item.save! }
start_at_row 1
read_attributes_from_file
end
end
seed.rb (simplified)
load_fixture("path-to-csv-file")
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论