从csv文件导入数据时无法批量分配受保护的属性
我有一个导入数据的表单,如下所示:
这是我的导入动作:
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
试试这个
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
source => http://www.funonrails.com/2012/01/csv-file-importexport-in-rails-3.html http://erikonrails.snowedin.net/?p=212
尝试使用Course.create(row.to_hash.symbolize_keys, :without_protection => true)
或者甚至将它与Dipak的建议结合起来。
或者,我更喜欢Course.create!(name: row['name'], code: row['code'])
。