How to code a UNION sql query with ActiveRecord
3
Not solved Solved
over 1 year ago

Hi buddies, My model Coupon has 3 fields I want to query on: start_date (Date object), end_date (Date object) and immortal (Boolean) I would like to do something like this:

Coupon.where("start_date <= Date.today AND (immortal = true OR end_date >= Date.today)")

But I only make bullshits :/ Please help me!

over 1 year ago

Regarding this tutorial, your code should work : http://sql.sh/cours/where/and-or (french) Did you have any displayed error message ?

over 1 year ago

It's OK I found that: DateTime::Infinity

over 1 year ago

Coupon.where("start_date =< ?", Date.today).where("immortal = ? OR end_date >= ?", true, Date.today) ?

over 1 year ago

[edit] what about using a method 'active?' in your model def active? immortal || ( Date.today >= start_date && Date.today <= expiration_date ) end Then Coupon.where( active? ) Be careful I changed the rules ('immortal' here prevails on any start/end date given) and I did not crash-tested this code.

over 1 year ago

Finally, this works:

Coupon.where("start_date =< ? AND (immortal = ? OR end_date >= ?)", Date.today , true, Date.today)

Thanks to all of you

Cancel
Submit your answer