活动记录:在on子句中使用哈希条件

时间:2012-02-02 06:49:59

标签: sql ruby-on-rails activerecord

试图弄清楚如何通过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))

1 个答案:

答案 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)