1
votes

I used this code to import my CSV file to table:

def Hotel.import(file)
  allowed_attributes = ["id", "name", "area", "short_name", "zip", "address", "tel", "fax", "staff_name", "information", "created_at", "updated_at"]
  CSV.foreach(file.path, headers: true) do |row|
    product = find_by_id(row["id"]) || new
    product.attributes = row.to_hash.select{ |k,v| allowed_attributes.include? k }
    product.save!
  end
end

def import
  Hotel.import(params[:file])
  redirect_to root_url, notice: "Product Imported."
end

However, this code only insert id, created_at, and updated_at field to table. The insert command show here:

INSERT INTO `hotels` (`created_at`, `updated_at`) VALUES ('2014-04-10 07:50:23', '2014-04-10 07:50:23')

I'm using rails 4.0 and ruby 2.0 to do this project. I check carefully to find error but I cannot find any problems here, so please tell me where I was wrong?

1
I can't find any errors. What does row.to_hash.select{ |k,v| allowed_attributes.include? k } return? - Stefan
Are the allowed_attributes actually allowed within your strong parameters? - rails4guides.com
@Stefan the original code is '*accessible_atributes' instead of row.to_hash.select{ |k,v| allowed_attributes.include? k }, however this original code cause error in rails 4, then I searched and find this solution. This code is the thing that make me confuesed. - dailammoc
insert p row.to_hash.select{ |k,v| allowed_attributes.include? k }, Kernel#p inspects the object and prints the result, you should see it in your log - Stefan
The line I've posted (p row.to_hash...) should print a hash, something like {"id" => "1", ...} - Stefan

1 Answers

0
votes

I found the problem is that: when I exported file to Desktop then I chose open it by LibreOffice Calc(Ubuntu 13.10), so it was wrong format. I changed by opening by gedit text editor and it worked correctly. Very stupid error!