如何使Active Record联接返回唯一对象? [英] How to make Active Record join return unique objects?
问题描述
我有一个简单的查询需求:查找自2013年1月1日以来下订单的用户列表。
在SQL中,这是一个非常简单的查询。 / p>
但是我正在使用Rails和Active Record。
所以我写道: User .joins(:orders).where( orders.created_at> ='2013-01-01 00:00:00')
在我们的数据库中,自2013年1月1日以来,有75位用户下了100笔订单。 (显然,有些用户下达了一个以上的订单。)
但是,上面的表达式返回100个用户。 (必须重复)。
我尝试了 User.joins(:orders).where( orders.created_at> ='2013- 01-01 00:00:00')。uniq
这也不起作用。
如何获得自2013年1月1日以来下订单的75位用户?
@dbjohn是正确的主意,但我想您想避免创建额外的对象。这是他的解决方案的一个小变体,让数据库为您完成唯一查询:
date = 2013-01- 01 00:00:00
User.joins(:orders).where( orders.created_at> =?,date).distinct
请注意,您可以重新排列方法的顺序以适合您认为最语义的内容,ActiveRecord会为您编写相同的SQL。
I have a simple query need: Find a list of users who made an order since Jan 1, 2013.
In SQL, it's a very simple query.
But I'm using Rails and Active Record.
So I wrote: User.joins(:orders).where("orders.created_at >= '2013-01-01 00:00:00'")
In our database, we have 100 orders made since 01/01/2013 by 75 users. (Some users made more than one order apparently.)
However, the expression above returns 100 users. (There must be duplicates.)
I tried User.joins(:orders).where("orders.created_at >= '2013-01-01 00:00:00'").uniq
That doesn't work either.
How can I get the 75 users who've made an order since 01/01/2013?
@dbjohn has the right idea, but I assume you want to avoid creating extra objects. Here's a slight variant on his solution, letting the database do the uniq-ing for you:
date = "2013-01-01 00:00:00"
User.joins(:orders).where("orders.created_at >= ?", date).distinct
Note that you can rearrange the order of methods to fit whatever you think is most semantic, and ActiveRecord will write the same SQL for you.
这篇关于如何使Active Record联接返回唯一对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!