Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make Active Record join return unique objects?

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?

like image 880
Zack Xu Avatar asked Mar 05 '13 17:03

Zack Xu


People also ask

How do I select unique records in SQL?

The SQL SELECT DISTINCT Statement The SELECT DISTINCT statement is used to return only distinct (different) values. Inside a table, a column often contains many duplicate values; and sometimes you only want to list the different (distinct) values.

Is ActiveRecord an ORM?

ActiveRecord is an ORM. It's a layer of Ruby code that runs between your database and your logic code.

What is ORM in ROR?

1.2 Object Relational Mapping Object Relational Mapping, commonly referred to as its abbreviation ORM, is a technique that connects the rich objects of an application to tables in a relational database management system.

What is ActiveRecord base?

ActiveRecord::Base indicates that the ActiveRecord class or module has a static inner class called Base that you're extending.


1 Answers

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

like image 186
amcaplan Avatar answered Sep 25 '22 22:09

amcaplan