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?
row.to_hash.select{ |k,v| allowed_attributes.include? k }return? - Stefanp row.to_hash.select{ |k,v| allowed_attributes.include? k },Kernel#pinspects the object and prints the result, you should see it in your log - Stefanp row.to_hash...) should print a hash, something like{"id" => "1", ...}- Stefan