我有一个活跃的记录查询,我试图像这样做
@past_agents = User.joins(properties: { video: { theme: :clients } }).where(clients: { id: @client },created_at: (@starttime) .. @previous).uniq.count
我被告知这种语法错了所以我把它改成了
@past_agents = User.joins(properties: { video: { theme: :clients } }).where("clients.id = :client AND created_at >= :start_date AND created_at <= :end_date",{client: @client, start_date: @starttime, end_date: @previous} ).uniq.count
然而它也不起作用。谁能告诉我正确的查询方式?
答案 0 :(得分:1)
当你处理日期范围时,第一种方式是我首选的写作方式。请参阅Active Record Range Conditions。
通过使用哈希语法,生成的查询将尝试利用BETWEEN
SQL语句。例如:
User.where(created_at: 6.months.ago..3.months.ago).to_sql
=> "SELECT \"users\".* FROM \"users\" WHERE (\"users\".\"created_at\" BETWEEN '2015-02-05 01:04:47.710505' AND '2015-05-05 01:04:47.710616')"
然而,你的第二次尝试却没有:
User.where("created_at >= :start_date AND created_at <= :end_date", start_date: 6.months.ago, end_date: 3.months.ago).to_sql
=> "SELECT \"users\".* FROM \"users\" WHERE (created_at >= '2015-02-05 01:07:26.998628' AND created_at <= '2015-05-05 01:07:26.998736')"
如果您已经有一个有效的SQL查询,我建议使用to_sql
来确定两个查询的差异。希望有所帮助!