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