简体   繁体   中英

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.

So, when I do

Banana.find(x).get_public I receive an Array of users (the ones suitable to that banana object).

The get_public method is like this:

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. I want to do something like this after: Banana.find(x).get_public.where(...) Any way to modify get_public and achieve this?

I am not sure I correcly undestood the problem, but I will try to help anyway.

As especified here

  • where returns an ActiveRecord::Relation
  • find (and its related dynamic methods) returns a single model object

So I suggest divide your queries into: 'joins' and 'where' fields. 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.

Hope I haven't missed the point too much :-)

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