user3358302
user3358302

Reputation: 2111

Ruby find by custom method?

I am trying to figure out a way to search on an ActiveRecord model by its usual rails 3.0 syntax mixed in with custom methods.

For example:

class User < ActiveRecord::Base
 def custom_method
   if [...]
     return true
   else 
     return false
   end     
 end
end

and I'd like to envoke this using ActiveRecord in such a way:

User.find(:all).where(custom_method is true)

Any ways to go about this? Apologies if the syntax isn't accurate for what I'm trying to convey.

EDIT: I'd like to clarify that custom_method used is fairly complex, so calling it instead of converting it to a sql syntax would be preferred.

Upvotes: 3

Views: 1706

Answers (1)

nort
nort

Reputation: 1615

This is typically implemented with a scope or with a class method

class User < ActiveRecord::Base
  scope :active, -> { where(status: 'active') }

  def self.hidden
    where(status: 'hidden')
  end
end

# Both a scope and class method are then used the the same way
User.active # User.where(status: 'active')

User.where(foo: 'bar').active # User.where(foo: 'bar', status: 'active')
User.where(foo: 'bar').hidden # User.where(foo: 'bar', status: 'hidden')

If the custom_method is too complex or relies on properties not stored in the database, you may need to resort to filtering the items in memory.

User.where(foo: 'bar').to_a.select(&:custom_method)

Upvotes: 6

Related Questions