In a Rails 3.2 model, was hoping to create a "to_csv" class method to generate CSV output from an ActiveRecord scope, like this:
class Post
# ...
def self.to_csv(options = {})
CSV.generate(options) do |csv|
scoped.each {|post| csv << record.attributes.values_at('title', 'text')}
end
end
end
I expected I could use it like this:
User.first.posts.to_csv
However, the method seems to be overridden by the Array #to_csv method. Even if I do this:
User.first.posts.scoped.to_csv
...and the result from User.first.posts.scoped is explicitly an ActiveRecord::Relation, I still hit the Array method. If I rename the method to something like "to_csvx" it works as expected.
I am hoping someone can explain how/why the ActiveRecord::Relation object preferentially hits the Array #to_csv method instead of the to_csv class method. While this (a class method expecting to be called by an AR scope) seems plausible, I am wondering if there's an inherent problem with the whole idea?