Reputation: 628
What is the proper way for where condition if i need to get rows in range for today and e.g. for yesterday? I mean something like this:
Model.where("created_at ? OR created_at ?",
Time.now - 3.hours..Time.now + 3.hours,
Time.now - 1.day - 3.hours..Time.now - 1.day + 3.hours)
Upvotes: 1
Views: 50
Reputation: 12340
Your query using or through Arel
model = Model.arel_table
Model.where(model[:created_at].eq(DateTime.now - 3.hours..DateTime.now + 3.hours).or(model[:created_at].eq(DateTime.now - 1.day - 3.hours..DateTime.now - 1.day + 3.hours)))
Upvotes: 0
Reputation: 29174
Model.where("(created_at between ? and ?) OR (created_at between ? and ?)",
3.hours.ago,
3.hours.from_now,
3.hours.ago.yesterday,
3.hours.from_now.yesterday)
Upvotes: 2
Reputation: 43318
You can do this:
Model.where("(created_at between ? and ?) OR (created_at between ? and ?)",
DateTime.now - 3.hours, DateTime.now + 3.hours,
DateTime.now - 1.day - 3.hours, DateTime.now - 1.day + 3.hours)
If you didn't have an OR
you could do:
Model.where(:created_at => (DateTime.now - 3.hours)..(DateTime.now + 3.hours))
but since you have and OR
you just have to "write it out" like I show above.
Upvotes: 2