Can't mass-assign protected attributes when im

2019-07-17 07:35发布

问题:

I have a form for import data like this:

<%= 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 %>

This is my import action:

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

But when i choose a file and press button Import in browser, i got error:

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

In my Course model, name and code already are attr_accessible:

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

What's wrong with my code?

Updated
This is my csv file:

name, code
ERP System, HT555DV01
Data Mining, HT459DV01

New code to create data

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

回答1:

try this

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

replace to

  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    

Update 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



回答2:

Try Course.create(row.to_hash.symbolize_keys, :without_protection => true) or even combine it with Dipak's suggestion.

Alternatively, I would prefer Course.create!(name: row['name'], code: row['code']).