我有以下方法可以返回当前月份正在运行的报纸展示位置的所有订单。订单has_many newspaper_placements。
def self.orders_with_placements_in_current_month(all_cc_mc)
filter_start = Date.today.beginning_of_month
filter_end = Date.today.end_of_month
all_orders = []
Order.where(client_companies_media_company_id: all_cc_mc).each do |x|
if x.newspaper_placements.count > 0
if (filter_start..filter_end).overlaps?(x.newspaper_placements.first.date..x.newspaper_placements.last.date)
all_orders << x
end
end
end
end
在Order上调用.where之后,我包含一个条件来查看newspaper_placement计数是否大于0,因为如果没有返回的位置,它后面的代码将会失败。有没有办法我只能在原始查询中返回newspaper_placement count大于0的订单?所以我想做的是:
Order.where(client_companies_media_company_id: all_cc_mc)
仅返回展示位置数&gt;的订单0,所以我可以消除后面的条件。
答案 0 :(得分:3)
Somethling喜欢:
Order.joins(:newspaper_placements).where(client_companies_media_company_id: all_cc_mc)