具有多个条件的范围基于多个条件的条件

是否有可能使用类似的东西

scope :state, ->(state) { merge(where("start_time = ?", Time.now.utc.beginning_of_day, Time.now.utc.beginning_of_day)) if state.include?("open") merge(where("end_time  ?", Time.now.utc.beginning_of_day)) if state.include?("upcoming") } 

如果我使用此范围,则只有最后一个范围可用。

例如:

  • 州([“即将来临”]) – >工作
  • state([“open”]) – >不使用的地方
  • state([“deleted”],[“coming”]) – >仅限使用即将发生的条件的地方

希望这能解决你的问题。

 scope :state, ->(state) {where(self.query_conditions(state), q: Time.now.utc.beginning_of_day))} def self.query_conditions(state) q = "" q+= "start_time <= :q and end_time >= :q" if state.include?("open") q+= " and end_time < :q" if state.include?("closed") q+= " and start_time > :q" if state.include?("upcoming") q end 

你应该可以使用

  scope :state, ->(state) { rel = all rel = rel.where("start_time <= ? and end_time >= ?", Time.now.utc.beginning_of_day, Time.now.utc.beginning_of_day) if state.include?("open") rel = rel.where("end_time < ?", Time.now.utc.beginning_of_day) if state.include?("closed") rel = rel.where("start_time > ?", Time.now.utc.beginning_of_day) if state.include?("upcoming") rel } 

请注意,你应该这样做

 state(["deleted", "upcoming"]) 

代替

 state(["deleted"], ["upcoming"]) 

您还可以使用Array.wrap来简化范围的使用:

  scope :state, ->(state) { state = Array.wrap(state) rel = all rel = rel.where("start_time <= ? and end_time >= ?", Time.now.utc.beginning_of_day, Time.now.utc.beginning_of_day) if state.include?("open") rel = rel.where("end_time < ?", Time.now.utc.beginning_of_day) if state.include?("closed") rel = rel.where("start_time > ?", Time.now.utc.beginning_of_day) if state.include?("upcoming") rel } 

在状态被包装的情况下,您可以通过以下两种方式使用范围:

 Model.state(['open', 'upcoming']) Model.state('open', 'upcoming')