Reputation: 4397
I'm having trouble applying a method to a collection within a model. Here's what my model looks like:
class MyModel < ActiveRecord::Base
def self.range(min, max)
where(id: min..max)
end
def self.my_collection_method
collect{|x| x.id}
end
end
This works:
MyModel.range(53, 55)
# [#<MyModel id: 53>, #<MyModel id: 54>]
And this works:
MyModel.range(53, 55).collect{|x| x.id}
# [53, 54]
But when I try to be fancy and use my_collection_method instead of collect, I get this error:
MyModel.range(53, 55).my_collection_method
# NoMethodError: undefined method `collect' for #<Class:0x007fcbad3efc30>
How can I get this to work?
Thanks for your time and wisdom!!
Upvotes: 0
Views: 2451
Reputation: 29599
I don't know what you're trying to achieve but you should be able to use it when you call scoped first
def self.my_collection_method
scoped.collect {|x| x.id}
end
without scoped
, you are trying to call self.collect
which is not a method of ActiveRecord
models. having scoped
there means you want to apply collect
to the current chain.
Upvotes: 3
Reputation: 11951
You've defined my_collection_method
on the model, not on a collection - they are separate classes. You can normally achieve what you want to do inside a model method:
class MyModel < ActiveRecord::Base
def self.range(min, max)
where(id: min..max)
end
def self.my_collection_method(min, max)
range(min, max).collect{|x| x.id}
end
end
The only other way is by attaching a method on the fly to the collection, but that's going to be pretty ugly.
Upvotes: 2