从populate.rake链接到资产csv文件

时间:2014-08-22 18:08:23

标签: ruby-on-rails csv ruby-on-rails-4 rake asset-pipeline

我需要从csv文件中加载一份食物列表,作为populate.rake的一部分。这将使我的网站开发速度更快。

我收到了这个错误:

NoMethodError: undefined method `path' for "./assets/food_db.csv":String

我在populate.rake中有这个方法

def make_foods
  Food.import("/assets/food_db.csv")        
end   

Inside food.rb

def self.import(file)
  CSV.foreach(file.path, headers: :true) do |row|
    self.create! row.to_hash
  end
end  

如何正确传递文件?

1 个答案:

答案 0 :(得分:1)

你快到了!

# food.rb
def self.import(file_path) # you receive here the file path as a String
  CSV.foreach(file_path, headers: :true) do |row|
    self.create! row.to_hash
  end
end

应该工作。


另外,我建议您使用文件的完整路径:

Food.import( Rails.root.join('app', 'assets', 'food_db.csv') )
# will be looking for a file in your application folder + `/app/assets/food_db.csv`
# For Ubuntu users, might look like this: `/home/<your_username>/<your_app_name>/app/assets/food_db.csv`