2

How can I turn a filter on an array of ActiveRecord objects into a scope?

For example turn this:

Users.all.collect { |u| u.has_super_powers? }

Into:

scope :supers, #something here

The point is that it can be used as a scope so Users.all is not always "all" like:

Users.undeleted.supers.find_by_this('that')

I thought maybe using lambda expressions in scopes is the way, but don't think that would work since I don't have access to records as the expression is added to a DB query and not run as a post step over the results.

1
  • 2
    What is has_super_powers? Scopes will only work on data inside the database, not Ruby methods. Commented Mar 7, 2012 at 0:07

1 Answer 1

3

It depends wether or not you can transform u.has_super_powers? into a database query. Sometimes it is possible, sometimes its not.

For example: If you have a database field has_super_powers (boolean column) in the users table you can create a scope on that:

scope :has_super_powers, where(:has_super_powers => true)

Now you can chain it together with other scopes:

User.undeleted.has_super_powers.find_by_this('that')
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.