Rails 4 how to call available_ attributes from a model

Hi, I am trying to use this one here on a Rails cast ( Import Excel csv file ). And I have an error on this lineproduct.attributes = row.to_hash.slice(*accessible_attributes)

undefined local variable or method Available Attributes for # `

this is my model.

class Product < ActiveRecord::Base
  require 'roo'
  validates_presence_of :price
  #attr_accessible :name, :price, :released_on #I removed this line (rails 4)


  def self.to_csv(options = {})
    CSV.generate(options) do |csv|
      csv << column_names
      all.each do |product|
        csv << product.attributes.values_at(*column_names)
      end
    end
  end

  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)
    when ".xls" then Roo::Csv.new(file.path)
    when ".xlsx" then Roo::Csv.new(file.path)
    else raise "Unknown file type: #{file.original_filename}"
    end
  end
end

end on my controller I defined product_params

def product_params
    params.require(:product).permit(:name, :price, :released_on)
  end

my csv I'm trying to import is as follows:

id,name,realased_on,price,created_at,updated_at
1,Acoustic Guitar,2012-10-03,3456.54,2013-12-09 00:00:23 UTC, 2012-12-08 23:45:46 UTC
+4
source share
4 answers

accessible_attributes , attr_accessible , 4 attr_accessible _, accessible_attributes , , . :

def accessible_attributes
 [col1_name, col2_name, ....]
end
+7

Railscast Rails 4.1 , _ row.to_hash.keys.

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(*row.to_hash.keys)
      product.save!
    end
end
+10

, , " ". , , Excel. , , . , .

+1

Using the decision as it did not work out for me. I needed to add a "me". to defining a method to make it work.

In another way, if the only place you call access_attributes is inside self.import, it defines the fields you are looking for as a local array variable.

def self.import(file)
    accessible_attributes = ['my_attribute_name1','my_attribute_name2', '...']
    spreadsheet = open_spreadsheet(file)
    header = spreadsheet.row(1)
    (2..spreadsheet.last_row).each do |i|
      row = Hash[[header, spreadsheet.row(i)].transpose]
      cae = find_by_id(row["id"]) || new
      cae.attributes = row.to_hash.slice(*accessible_attributes)
      cae.save!
   end
end
+1
source

All Articles