Marcin Doliwa
Marcin Doliwa

Reputation: 3659

How to combine two activerecord queries?

Lets say we have Event model, and SearchEngine class which performs searches on events.

SearchEngine has search method.

class SearchEngine
  def search(event_scope)
    return Event.all if event_scope.nil?
    //event_scope combined with Event.where('name = ?','test')
  end
end

I'd like to be able to pass event_scope like this:

SearchEngine.new.search(Event.where('start_time > ?',Time.now))

And the result would be the same as:

Event.where('start_time > ?',Time.now).where('name = ?','test')

How can I do this?

Upvotes: 2

Views: 1544

Answers (1)

Matouš Borák
Matouš Borák

Reputation: 15934

Scopes provide a merge method to merge with another scope, so this should work:

class SearchEngine
  def search(event_scope)
    return Event.all if event_scope.nil?
    Event.where('name = ?','test').merge(event_scope)
  end
end

Upvotes: 4

Related Questions