2

我有一个这样的导入数据表格:

<%= form_tag({ controller: 'courses', action: :import }, multipart: true) do %> 
  <%= label_tag 'file', 'Import data' %>
  <%= file_field_tag 'file' %>
  <%= submit_tag "Import", name: nil, class: 'btn' %>
<% end %>

这是我的导入操作:

def import
  require 'csv'

  csv_text = File.read(params[:file].tempfile.to_path.to_s)
  csv = CSV.parse(csv_text, headers: true )
  csv.each do |row|
    row = row.to_hash.with_indifferent_access
    Course.create(row.to_hash.symbolize_keys)
  end
  flash[:success] = "Successfully import data."
  redirect_to courses_url
end

但是当我在浏览器中选择一个文件并按下按钮Import时,我得到了错误:

ActiveModel::MassAssignmentSecurity::Error in CoursesController#import
Can't mass-assign protected attributes: Name, Code

在我的Course模型中,name并且code已经是 attr_accessible:

class Course < ActiveRecord::Base
  attr_accessible :code, :name
end

我的代码有什么问题?

更新
这是我的 csv 文件:

name, code
ERP System, HT555DV01
Data Mining, HT459DV01

创建数据的新代码

csv.each do |row|
  Course.create!(name: row[0], code: row[1])
end
4

2 回答 2

3

尝试这个

csv.each do |row|
  row = row.to_hash.with_indifferent_access
  Course.create(row.to_hash.symbolize_keys)
end

替换为

  csv.each do |row|
    Course.create(row.to_hash)
  end

更新

csv_file = File.read(params[:file].tempfile.to_path.to_s)
csv = CSV.parse(csv_file, :headers => true) 
csv.each do |row|
   Course.create!(:name => row[0], :code => row[1])    
end    

更新 2

csv_file = params[:file].read
CSV.parse(csv_file) do |row|
   course = Course.create(row)
   course.save
end

来源 => http://www.funonrails.com/2012/01/csv-file-importexport-in-rails-3.html http://erikonrails.snowedin.net/?p=212

于 2012-11-06T08:38:13.657 回答
1

尝试Course.create(row.to_hash.symbolize_keys, :without_protection => true)甚至将其与 Dipak 的建议结合起来。

或者,我更喜欢Course.create!(name: row['name'], code: row['code']).

于 2012-11-06T08:47:40.683 回答