简体   繁体   English

Rails活动记录之间创建的特定ID

[英]rails active record specific id created between

i have a active record query that i attempted to make like this 我有一个试图进行这样的活动记录查询

@past_agents = User.joins(properties: { video: { theme: :clients } }).where(clients: { id: @client },created_at: (@starttime) .. @previous).uniq.count

i was told that this syntax is wrong so i changed it to 有人告诉我这种语法是错误的,所以我将其更改为

@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

however its not working either. 但是它也不起作用。 can someone tell me the proper way to do the query? 有人可以告诉我进行查询的正确方法吗?

When you're dealing with a date range, the first way is my preferred way of writing it. 当您处理日期范围时,第一种方法是我首选的书写方式。 See Active Record Range Conditions . 请参阅活动记录范围条件

By using the hash syntax, the resulting query will try to take advantage of the BETWEEN SQL statement. 通过使用哈希语法,结果查询将尝试利用BETWEEN SQL语句。 For example: 例如:

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')"

Whereas, your second attempt does not: 而您的第二次尝试却没有:

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')"

If you have a working SQL query already, I would suggest using to_sql to determine the differences in the two queries. 如果您已经有一个有效的SQL查询,我建议使用to_sql确定两个查询中的差异。 Hope that helps! 希望有帮助!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM