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

2
  • have you gonna through rails scopes, please go through it .. this is may be you are looking for stackoverflow.com/questions/4869994/… Commented Jul 6, 2016 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'. Commented Jul 6, 2016 at 11:08

1 Answer 1

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