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