I don't know even if its possible? I need to use instance method with/within scope. Something like this:
scope :public, lambda{ where ({:public => true}) }
and call instance method(complete?) on each record to see if it is completed. public scope here should return all records that are public and are completed and completion of a record is determined by a instance method 'complete?'
Any possibility?
Thanks
Scopes are about generating query logic using ARel. If you can't represent the logic of the complete? method in SQL then you're kind of stuck
Scopes - in rails 3 at least - are meant for chaining together query logic without returning a result set. If you need a result set to do your testing for complete you'll need to do something like
class MyModel < ActiveRecord::Base
scope :public, lambda{ where ({:public => true}) }
def self.completed_public_records
MyModel.public.all.select { |r| r.completed? }
end
end
# elsewhere
MyModel.completed_public_records
Or if you need more flexibility
class MyModel < ActiveRecord::Base
scope :public, lambda{ where ({:public => true}) }
# some other scopes etc
def self.completed_filter(finder_obj)
unless finder_obj.is_a?(ActiveRecord::Relation)
raise ArgumentError, "An ActiveRecord::Relation object is required"
end
finder_obj.all.select { |r| r.completed? }
end
end
# elsewhere
MyModel.completed_filter(MyModel.public.another_scope.some_other_scope)
I created a rubygem for this exact problem a few months back when I had the same problem.
It allows you to add methods that work on the result set of the query, but abstracts the methods into another class so its not muddled in with your model.
Check it out: https://github.com/coryodaniel/collectively