Rails, ActiveRecord multiple query results in one instance variable

1.6k views Asked by At

What I'm trying to accomplish (if it's possible) is to create a query that will essentially do 2 searches and return the results into one instance variable. The reason for this is because, I am using the will_paginate gem and it only allows me to render an array of objects from the single query and doesn't accept anything else to be pushed onto that array being sent to the template.

i.e.

My events_controller.rb

#returns all events that match query
@events_search_result = Events.search(params[:event][:query])

#returns all events where column 'repeats' is nil
@events_not_repeat = Events.where.not(repeats: nil)
@events_not_repeat.each do |event|
  #'schedule.occurs_on?' methods coming from different gem. Not relative in the outcome of the array of objects to be rendered. 
  if event.schedule.occurs_on?(params)
    @events_search_result << event
  end
end

Pushing these two array of objects gives me the desired result, but when trying to render @events_search_result to the template, I get the error...

NoMethodError - undefined method 'total_pages' for #<Array:0x00000000>: Which is coming from the will_paginate gem.

Ideally, I'd like the two queries to happen in one shot, which is what I believe will solve my issue. I've looked at the ActiveRecord Query Interface but due to my inexperience, I'm not that familiar with the query combinations that can be achieved.

Any advice will help a lot. Been stuck on this issue for quite a while now and tried a bunch of workarounds. Apologize in advance if my examples aren't descriptive enough but I'd be happy to fill in the details if need be. Thanks!

3

There are 3 answers

0
Nigel Earle On

On the instance variable being sent to the template call ... @combined_events_of_both_queries.paginate(:page => params[:page], :per_page => 5) to change it to a will_paginate array to be iterated over.

1
Chitrank Samaiya On

Since your both objects are of same model, you can add one object to other and apply pagination.

for eg:

  @events_search_result = Events.search(params[:event][:query])
  @events_not_repeat = Events.where.not(repeats: nil)
  @combined_events = @events_search_result + @events_not_repeat
  @combined_events.apply_will_paginate
0
Amit Thawait On

You need to require will_paginate/array in your will_paginate initializer file to fix your issue :

require 'will_paginate/array'