81637

Can't mass-assign protected attributes when import data from csv file

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?

<strong>Updated</strong> This is my csv file:

name, code ERP System, HT555DV01 Data Mining, HT459DV01

<strong>New code to create data</strong>

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

Answer1:

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

<strong>Update</strong>

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

<strong>Update 2</strong>

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

Answer2:

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']).

Recommend

  • Refactor association out of view from a loop
  • DelayedJob: How to solve the problem “Job failed to load”?
  • Streaming wrapper around program that writes to multiple output files
  • Iterate over digits of integers inside of array
  • How to use ruby-on-rails fixtures for setting up (external) data that does not belong to the rails a
  • ActiveRecord: abort datetime parsing if value is invalid
  • Seahorse::Client::NetworkingError Amazon S3 file upload with rails
  • FactoryGirl factory with Trait(s) that returns a Hash with stringed keys
  • Application will not launch from command line full path, but will after CDing to directory
  • Ruby on Rails Active Record RANDOM() always the same within a loop
  • Batch to process files one by one
  • rails 5 carrierwave no route matches for image
  • How to remove comma or any characters from Python dataframe column name
  • Error while re-opening sound file in python
  • SSH in Bash Script Messing Up File Read
  • Wrap C++ function using Boost Reflect or another C++ reflection library
  • android Navigation Bar hiding and persantage of usable screen overlap
  • Javascript CORS - No 'Access-Control-Allow-Origin' header is present
  • Textfile Structure (tables)
  • Rails Find when some params will be blank
  • Content-Length header not returned from Pylons response
  • Is there a javascript serializer for JSON.Net?
  • Java Scanner input dilemma. Automatically inputs without allowing user to type
  • Master page gives error
  • How to apply VCL Styles to DLL-based forms in Inno Setup?
  • align graphs with different xlab
  • Warning: Can't call setState (or forceUpdate) on an unmounted component
  • Unanticipated behavior
  • using conditional logic : check if record exists; if it does, update it, if not, create it
  • InvalidAuthenticityToken between subdomains when logging in with Rails app
  • SQL merge duplicate rows and join values that are different
  • LevelDB C iterator
  • sending mail using smtp is too slow
  • Unable to use reactive element in my shiny app