RailsCasts Pro episodes are now free!

Learn more or hide this

onkelyoo's Profile

GitHub User: onkelyoo

Comments by

Avatar

i got the mistake. I installed the gem 'protected attributes'. I also forgot to define the attr_accessible. The working version in Rails 4 looks so:

ruby
attr_accessible :id, :url, :price_ek
def self.import(file)
    spreadsheet = open_spreadsheet(file)
    header = spreadsheet.row(1)
    (2..spreadsheet.last_row).each do |i|
      row = Hash[[header, spreadsheet.row(i)].transpose]
      product = find_by_id(row["id"]) || new
      product.attributes = row.to_hash.slice(*accessible_attributes)
      product.save!
    end
  end

  def self.open_spreadsheet(file)
    case File.extname(file.original_filename)
    when ".csv" then Roo::Csv.new(file.path, csv_options: {col_sep: ";"})
    when ".xls" then Roo::Excel.new(file.path)
    when ".xlsx" then Roo::Excelx.new(file.path)
    else raise "Unknown file type: #{file.original_filename}"
    end
  end
Avatar
ruby
Controller:
def import
    Blog.import(params[:file])
    redirect_to blogs_path, notice: "Blogs importiert!"
 end

Model:

def self.import(file)
    allowed_attributes = [ "id","url","price_ek","price_new","si", "pr", "status" "updated_at"]
    spreadsheet = open_spreadsheet(file)
    header = spreadsheet.row(1)
    (2..spreadsheet.last_row).each do |i|
      row = Hash[[header, spreadsheet.row(i)].transpose]
      blog = Blog.find_by_id(row["id"]) || new
      blog.attributes = row.to_hash.select { |k,v| allowed_attributes.include? k }
      blog.save!
    end
  end


  def self.open_spreadsheet(file)
    case File.extname(file.original_filename)
    when ".csv" then Roo::Csv.new(file.path)
    when ".xls" then Roo::Excel.new(file.path)
    when ".xlsx" then Roo::Excelx.new(file.path)
    else raise "Unknown file type: #{file.original_filename}"
    end
  end

I used this Code for Rails 4 and it is creating the rows in the DB, but all values (url, pr, etc) are nil. Any suggestions what I have done wrong?