1

I wondering if it is posible to use a model instance method as a where clause query. I mean. I have a model School with a method defined

class School < ActiveRecord::Base

  def my_method
    users.where(blablabla).present?
  end

end

Is it posible to get something like:

School.all.where(my_method: true)

I know that I can do something like:

School.all.map{|x| x if x.my_method}

But this way has a huge penalization in performance compared to where query. Furthermore, the return of what I'm searching is an ActiveRecord Relation and map returns an array.

UPDATE:

Also there is another way to do it like:

School.all.joins(:users).where("users.attribute = something")

But this do not fit exactly what I want for several reasons.

Thanks in advance

Marc Pursals
  • 762
  • 1
  • 8
  • 23
  • have you gonna through rails scopes, please go through it .. this is may be you are looking for http://stackoverflow.com/questions/4869994/what-is-scope-named-scope-in-rails – chaitanya Jul 06 '16 at 10:44
  • Your question would probably be easier to digest if you could state what your methods are supposed to achieve. You should explain your design decision for them. Are you trying to evaluate a method and send its results to the 'where' or are you trying to dynamically create conditions for 'where'. –  Jul 06 '16 at 11:08

1 Answers1

1

I don't really know the relations between your models.

but where clause gets a hash of key - value. So you can for example return the ID's of the users in a some kind of a hash and then use it.

def my_method
  {user_id: users.where(blablabla).ids}
end

and use it:

School.all.where(my_method)
Ziv Galili
  • 1,405
  • 16
  • 20