My Discount model has one Period association. I am trying to write a scope that select discounts that starts today, this includes:
- when it has a period, select those periods that begins today.
- when it does not have a period, select those discounts which were created between yesterday and today
My current query can do the first requirement (actually a bit complex than this):
def self.begins_today
joins(:event).where("begin = ?", today)
end
However how can I achieve requirement 2?
I was thinking of using SQL UNION command, but I think it can’t work as a scope.
I’m assuming event contains the period association?
In any case you want a left join between the discounts table and the periods table. This will give you the period data to do the
begin = todaywhere clause, and null if there is no period. Thus the SQL to select the data would bein rails you should be able to achieve this as follows:
Unfortunately you need the use SQL statements rather than letting rails create it for you as: