0

我在我的控制器中的 index 操作下有这个:

format.csv do

    @coasters = Coaster.all
    render text: @coasters.to_csv

end

但是当我运行它时,我得到: undefined method `to_csv' for # I just can;t see where I wrong?

to_csv 方法在这里:

def self.to_csv
    CSV.generate do |csv|
      csv << column_names
      all.each do |coaster|
        csv << coaster.attributes.values_at(*column_names)
      end
    end
  end

有什么想法吗?

4

2 回答 2

3

Your class method to_csv works on relations (scopes), so just write @coasters = Coaster.scoped instead @coasters = Coaster.all:

format.csv do

    @coasters = Coaster.scoped
    render text: @coasters.to_csv

end

Explanation:

Your method to_csv is declared with self. so this is class method. This method can be executed only on Coaster class, not over object or array of objects:

 Coaster.to_csv  #good
 Coaster.find(1).to_csv #error - Coaster object: undefined method 'to_csv'
 Coaster.where('id>5').to_csv #good
 Coaster.where('id>5').all.to_csv #error - return array of objects
 Coaster.all.to_csv #error

Last 3 lines are related with Rails 3 ActiveRecord::Relation: link1, link2. All class method can be executed on ActiveRecord::Relation object, but remember that Coaster.all returns array of objects, not relation.

Coaster.scoped returns ActiveRecord::Relation for all objects: http://apidock.com/rails/ActiveRecord/Scoping/Named/ClassMethods/scoped

于 2012-07-22T13:39:02.310 回答
1

Coaster.all返回一个不是异常类的数组。所以,当你尝试提高它时,你会得到你所看到的错误

于 2012-07-22T10:23:31.443 回答