rake db:seed无法读取CSV

时间:2014-12-17 02:08:22

标签: ruby-on-rails postgresql csv rake

我打算从CSV文件填充我的PostgreSQL数据库,但当我rake db:seed时,我收到了这个错误:

rake aborted!
ActiveRecord::StatementInvalid: PG::InsufficientPrivilege: ERROR:  could not open file "/home/spondbob/projects/rhsystem/db/data/doctors.csv" for reading: Permission denied
: COPY doctors(
    name,
    address,
    phone,
    field_id,
    is_active,
    email,
    encrypted_password,
    reset_password_token,
    reset_password_sent_at,
    remember_created_at,
    sign_in_count,
    current_sign_in_at,
    last_sign_in_at,
    current_sign_in_ip,
    last_sign_in_ip) 
FROM '/home/spondbob/projects/rhsystem/db/data/doctors.csv' WITH DELIMITER ',' CSV HEADER
/home/spondbob/.rvm/gems/ruby-2.1.5@rhsystem/gems/activerecord-4.1.8/lib/active_record/connection_adapters/postgresql/database_statements.rb:128:in `async_exec'

...

我不确定为什么它没有读取权限,我已经确定了权限并且数据库连接已经建立。这是文件权限:

$ ls -l db/data                     
total 56
-rwxr-xr-x 1 spondbob users   775 Dec 17 12:46 doctors.csv
...

我的seeds.rb代表第一张桌子:

connection = ActiveRecord::Base.connection()
connection.execute("COPY doctors(
    name,
    address,
    phone,
    field_id,
    is_active,
    email,
    encrypted_password,
    reset_password_token,
    reset_password_sent_at,
    remember_created_at,
    sign_in_count,
    current_sign_in_at,
    last_sign_in_at,
    current_sign_in_ip,
    last_sign_in_ip) 
FROM '#{Rails.root.join('db','data')}/doctors.csv' WITH DELIMITER ',' CSV HEADER")

感谢任何帮助。感谢。

1 个答案:

答案 0 :(得分:1)

为此创建一个rake任务:

desc "Imports a CSV file into an ActiveRecord table"
task :csv_import, :filename, :model, :needs => :environment do |task,args|
  lines = File.new(args[:filename]).readlines
  header = lines.shift.strip
  keys = header.split(',')
  lines.each do |line|
    params = {}
    values = line.strip.split(',')
    keys.each_with_index do |key,i|
      params[key] = values[i]
    end
    Module.const_get(args[:model]).create(params)
  end
end

然后像这样使用它:

  

rake csv_import file.csv model