Marc Pursals
Marc Pursals

Reputation: 792

Using method in a where clause Rails Ruby Active Record

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

Upvotes: 1

Views: 2830

Answers (1)

Ziv Galili
Ziv Galili

Reputation: 1445

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)

Upvotes: 1

Related Questions