Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

instance method in scope

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

like image 706
bikashp Avatar asked Jun 01 '11 09:06

bikashp


1 Answers

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)
like image 168
Chris Bailey Avatar answered Sep 22 '22 15:09

Chris Bailey