WHERE条款与OR

时间:2013-08-09 07:10:18

标签: ruby-on-rails-3 activerecord

目前我有以下一行:

scope :within_date_range, ->(start_date, end_date) {
  where("(start_date BETWEEN ? AND ?) OR (end_date BETWEEN ? AND ?)", start_date, end_date, start_date, end_date)
}

是否有更优雅的方式使用类似的东西?

scope :within_date_range, ->(start_date, end_date) {
  where((:start_date => start_date..end_date) OR (:end_date => start_date..end_date))
}

1 个答案:

答案 0 :(得分:0)

使用Arel

t = Post.arel_table
Post.where(t[:start_date].eq(start_date..end_date).or(t[:end_date].eq(start_date..end_date)))

或者

Post.where('start_date BETWEEN (:start_date) AND (:end_date) OR end_date BETWEEN (:start_date) AND (:end_date)', :start_date => (start_date..end_date), :end_date => (start_date..end_date))