试图弄清楚如何通过Active Record进行查询并保持尊严。 sql的最终结果应如下所示:
... left join works on clients.id = works.client_id and works.performed_on >= '2012-01-21' and works.performed_on <= '2012-01-28'...
如果日期范围在 WHERE 子句中,我可以使用这样的哈希条件:
where(:performed_on => (date1..date2))
但是,我需要 ON 子句中的范围。除了痛苦地写出完整的东西之外,还有更好的想法吗?
在我看来,像下面这样的东西是完美的:
Client.joins('left join works').on('clients.id' => 'works.client_id', 'works.performed_on' => (date1..date2))
答案 0 :(得分:2)
您可以在WHERE
子句中过滤结果,而不是ON
子句。
Client.joins(:works).where(:works => {:performed_on => (date1..date2)})
如果必须在ON
子句中过滤结果,那么首先构造JOIN sql:
join_sql = Client.send(:sanitize_sql_for_conditions, [
"LEFT JOIN works ON clients.id = works.client_id AND (
works.performed_on >= ? AND works.performed_on <= ? )",
date1, date2])
Client.joins(join_sql)