2

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?

3
  • Have you tried including ActiveRecord::QueryMethods in your class to get relation query methods? Commented Aug 28, 2013 at 16:29
  • What is pb.inject(:'&') supposed to be doing in this case and have you tested it's behavior? Commented Aug 28, 2013 at 16:37
  • it's the "logic AND" between the itens of the array. Commented Aug 30, 2013 at 16:10

1 Answer 1

1

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 :-)

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.