Jump to content

The ultimate community for Ruby on Rails developers.


Photo

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

ruby-on-rails-4 csv

  • Please log in to reply
No replies to this topic

#1 dailammoc

dailammoc

    Dispatcher

  • Members
  • 38 posts
  • Location/

Posted 11 April 2014 - 01:46 AM

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?







Also tagged with one or more of these keywords: ruby-on-rails-4, csv

0 user(s) are reading this topic

0 members, 0 guests, 0 anonymous users