[英]Get rails ActiveRecord instead of Array of objects for multiple queries
I have a table that stores queries that return a list of users. 我有一个表,用于存储返回用户列表的查询。 I then have a method "get_public" to a "Banana" model that execute multiple queries using logic AND between them.
然后,我有一个“香蕉”模型的方法“ get_public”,可以使用它们之间的逻辑与执行多个查询。
So, when I do 所以,当我这样做
Banana.find(x).get_public
I receive an Array of users (the ones suitable to that banana object). Banana.find(x).get_public
我收到了一个用户数组(适用于该香蕉对象的用户)。
The get_public method is like this: get_public方法是这样的:
def get_public
pb = []
banana_queries.each do |q|
pb << User.find_by_sql(q.query)
end
pb.inject(:'&')
end
But, would be great if I could get ActiveRecord::Relation instead. 但是,如果我能获得ActiveRecord :: Relation会很棒。 I want to do something like this after:
Banana.find(x).get_public.where(...)
Any way to modify get_public and achieve this? 我想在以后做这样的事情:
Banana.find(x).get_public.where(...)
方法可以修改get_public并实现它?
I am not sure I correcly undestood the problem, but I will try to help anyway. 我不确定我是否正确地解决了这个问题,但是无论如何我都会尽力帮助。
So I suggest divide your queries into: 'joins' and 'where' fields. 因此,我建议将您的查询分为:“ joins”和“ where”字段。 Your new code should look like something like this:
您的新代码应如下所示:
pb << User.joins(q.query_joins).where(q.query_where)
Also find methods will are deprecated in rails 4, so using where is recommended. 在轨4中,不推荐使用find方法,因此建议使用where。
Hope I haven't missed the point too much :-) 希望我不要错过太多的重点了:-)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.