Rails 4导出为csv:undefined方法`attributes'

时间:2016-03-07 10:36:15

标签: ruby-on-rails csv

我正在尝试将数据导出到csv文件。我的代码

@products = Product.all

    respond_to do |format|
      format.csv { render text: @products.to_csv }
    end

在我的模特中

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

这不起作用。我收到此错误

NoMethodError in ProductsController#index
undefined method `attributes' for #<Class:0x000000047e91c8>

我在Rails 4和ruby 2.2中。我该如何解决这个问题?

2 个答案:

答案 0 :(得分:1)

  

ProductsController中的NoMethodError #index undefined方法   `属性&#39;对于类:0x000000047e91c8

正如我所说,您应该使用product.attributes.values_at(*column_names)代替self.attributes.values_at(*column_names)

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

Source

答案 1 :(得分:0)

您属于模型的类方法(def self.to_csv)。在此方法中,self是类Product而不是产品实例。但是您想要访问产品实例的属性。您遍历all个产品对象。因此,您需要访问当前的产品对象,每次迭代都会为您提供(|product|)。因此,请尝试使用product.attributes代替self.attributes