简体   繁体   中英

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

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM