Rails 4如何从Model调用accessible_attributes

Pap*_*nho 3 ruby ruby-on-rails ruby-on-rails-4

嗨我在Rails演员(导入csv Excel文件)上尝试这个tuto .我在这条线上有错误product.attributes = row.to_hash.slice(*accessible_attributes)

undefined local variable or method##的accessible_attributes'

这是我的模特.

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
Run Code Online (Sandbox Code Playgroud)

在我的控制器上结束我定义了product_params

def product_params
    params.require(:product).permit(:name, :price, :released_on)
  end
Run Code Online (Sandbox Code Playgroud)

我想要导入的我的csv看起来像这样:

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
Run Code Online (Sandbox Code Playgroud)

小智 9

在Rails 4.1下处理这个Railscast时,我通过用row.to_hash.keys替换accessible_attributes来获得工作方法.

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
Run Code Online (Sandbox Code Playgroud)

  • 这与说'product.attributes = row.to_hash`是一样的,因为你从`row`对象获得所有键.它可以工作,但Railscast代码的目的是仅采用Product模型中具有匹配属性的行中的列.(通常电子表格的列数比模型中所需的列数多.)由于Rails 4不使用`attr_accessible`,因此您必须在上面接受的答案中明确命名所需的键. (6认同)

Har*_*arI 6

实际上accessible_attributes获取attr_accessible在模型中声明的列但是在rails 4中他们已经删除了attr_accessiblefrom模型并使用了strong_parameter而不是那样,因此accessible_attributes在他的模型中创建一个同名的方法然后在该方法内部声明了你想要的列数组.如:

def accessible_attributes
 [col1_name, col2_name, ....]
end
Run Code Online (Sandbox Code Playgroud)