0
votes

I have a simple csv import functionality and I am getting this error

Can't mass-assign protected attributes: First Name Last Name Email

I am very surprised this is happening since I do have attr_accessible for these fields. Here is my info.rb model code

attr_accessible :email, :fname, :lname

def self.import(file)
  CSV.foreach(file.path, headers: true) do |row|
    Contact.create! row.to_hash
  end
end

My CSV is test.csv (the export is working fine, only the import of data is giving this error)

First Name  Last Name   Email
John    Smith   [email protected]
Janen   Smith   [email protected]
2
what is the version of rails '4' ?? - Rajarshi Das

2 Answers

2
votes

Try This stackoverflow answer. This might solve your problem.

def self.import(file)
    CSV.foreach(file.path, headers: true) do |row|
      Contact.create!( :fname => row[0], 
                       :lname => row[1], 
                       :email => row[2] 
                      ) 
    end
end
2
votes

You only have attr_accessible defined for :email, :fname, :lname.

Your csv contains First Name, Last Name, Email and they are different from :email, :fname, :lname.

So, you need to add the following to make it work:

attr_accessible :"First Name", :"Last Name", :Email

Update:

While this solution works, it does not look pretty!

On your second comment:

Btw, right now, I have to keep the 1st row as fname,lname,email, is there anyway the user can uplaod file with - FirstName,LastName,Email which can be mapped to fname,lname,email

For this, the solution presented by @monangik is perfect!