从 csv 文件导入数据时无法批量分配受保护的属性



我有一个类似导入数据的表单:

<%= 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型号中,namecode已经是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

update

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.htmlhttp://erikonrails.snowedin.net/?p=212

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

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

最新更新