我有一个用于导入数据的表单,如下所示:
<%= 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
但是当我选择一个文件并在浏览器中按导入
按钮时,出现错误:
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
最佳答案
试试这个
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
关于ruby-on-rails - 从 csv 文件导入数据时无法批量分配 protected 属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13247149/