How to make Active Record join return unique objects?

拜拜、爱过 提交于 2019-12-08 14:30:25

问题


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?


回答1:


@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.




回答2:


User.joins(:orders).
    where("orders.created_at >= '2013-01-01 00:00:00'").
    group('users.id')

group method will chain to the query and give you a list of unique records.




回答3:


Rails has added uniq since version 3.2.1 so now you can use uniq

http://apidock.com/rails/ActiveRecord/QueryMethods/uniq



来源:https://stackoverflow.com/questions/15230568/how-to-make-active-record-join-return-unique-objects

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!