Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/ruby-on-rails/68.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby on rails 在where子句中使用方法Rails Ruby活动记录_Ruby On Rails_Activerecord_Where Clause - Fatal编程技术网

Ruby on rails 在where子句中使用方法Rails Ruby活动记录

Ruby on rails 在where子句中使用方法Rails Ruby活动记录,ruby-on-rails,activerecord,where-clause,Ruby On Rails,Activerecord,Where Clause,我想知道是否可以使用模型实例方法作为where子句查询。我是说。我有一所方法明确的示范学校 class School < ActiveRecord::Base def my_method users.where(blablabla).present? end end 我知道我可以做一些事情,比如: School.all.where(my_method: true) School.all.map{|x| x if x.my_method} 但与where查询相比,这

我想知道是否可以使用模型实例方法作为where子句查询。我是说。我有一所方法明确的示范学校

class School < ActiveRecord::Base

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

end
我知道我可以做一些事情,比如:

School.all.where(my_method: true)
School.all.map{|x| x if x.my_method}
但与where查询相比,这种方法在性能上有很大的损失。此外,我搜索的返回是一个ActiveRecord关系,map返回一个数组

更新:

还有另一种方法,如:

School.all.joins(:users).where("users.attribute = something")
但这并不完全符合我的要求,原因有几个


提前谢谢

我真的不知道你们型号之间的关系

但是where子句获取键值的散列。 例如,您可以在某种散列中返回用户的ID,然后使用它

def my_method
  {user_id: users.where(blablabla).ids}
end
并使用它:

School.all.where(my_method)

你要通过rails望远镜吗,请通过它。。这可能是你正在寻找的,如果你能说明你的方法应该达到什么目的,你的问题可能会更容易理解。你应该向他们解释你的设计决定。您是在尝试评估方法并将其结果发送到“where”还是在尝试为“where”动态创建条件。