如何组合两个activerecord查询?

时间:2016-03-31 13:05:47

标签: ruby-on-rails ruby ruby-on-rails-4 rails-activerecord

让我们说我们有Event模型和SearchEngine类来执行事件搜索。

SearchEnginesearch方法。

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

我希望能够像这样传递event_scope:

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

结果与:

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

我该怎么做?

1 个答案:

答案 0 :(得分:4)

范围提供merge method与另一个范围合并,因此这应该有效:

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