Khash
Khash

Reputation: 2570

How to have a non query based scope in Rails

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.

Upvotes: 2

Views: 113

Answers (1)

spas
spas

Reputation: 1934

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')

Upvotes: 3

Related Questions