ruby-on-rails - Rails 4 如何从模型中调用 accessible_attributes

标签 ruby-on-rails ruby ruby-on-rails-4

您好,我正在尝试这个 tuto on Rails cast ( Importing csv Excel file )。我在这一行 product.attributes = row.to_hash.slice(*accessible_attributes)

上遇到错误

undefined local variable or methodaccessible_attributes' for #`

这是我的模型。

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

在我的 Controller 上结束,我定义了 product_params

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

我尝试导入的 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

最佳答案

在 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

关于ruby-on-rails - Rails 4 如何从模型中调用 accessible_attributes,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20854347/

相关文章:

javascript使模式在rails中提交表单

css - 如何将 Ruby 哈希转换为 CSS 规则?

ruby-on-rails - 无法为模型创建 FactoryGirl 的工厂

ruby - 在 Ruby 中使用 Parslet 的缩进敏感解析器?

ruby - Faye 在使用 https Rails 应用程序和 http faye 应用程序时无法工作

ruby-on-rails - Rails 4,如何正确配置smtp设置(gmail)

ruby-on-rails - Rails STI 类自动初始化

javascript - 如何使用 .js.erb 将 ruby​​ 数据结构转换为 javascript 数据结构?

ruby-on-rails - 如何使用 Windows 开始使用 Ruby on Rails

ruby - 验证框架的替代 Rails