Rails 4 如何从模型调用accessible_attributes [英] Rails 4 how to call accessible_attributes from Model

查看:38
本文介绍了Rails 4 如何从模型调用accessible_attributes的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在 Rails 上使用这个教程(导入csv Excel 文件).我在这一行出现错误 product.attributes = row.to_hash.slice(*accessible_attributes)

Hi I'm trying this tuto on Rails cast (Importing csv Excel file). And I'm having an error on this line product.attributes = row.to_hash.slice(*accessible_attributes)

未定义的局部变量或方法accessible_attributes' for #`

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

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

end on my controller I defined the product_params

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

我尝试导入的 csv 如下所示:

my csv that I'm trying to import looks like this:

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

推荐答案

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

Actually accessible_attributes fetch that columns which are declare attr_accessible in model but in rails 4 they have removed the attr_accessible from model and used the strong_parameter instead of that so for this make an method of same name accessible_attributes in his model then inside that method declare that columns array which are you want. Such as:

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

这篇关于Rails 4 如何从模型调用accessible_attributes的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆