Question

For example, I have 2 models:

Purchase (belongs_to :users) User (has_many :purchases)

I want to select all users that have at least one purchase.

In SQL I would write like this:

SELECT * FROM `users` WHERE `id` IN (SELECT DISTINCT `buyer_id` FROM  `purchases`)

And one more question: are there any full documentation or book that cover Arel?

Was it helpful?

Solution

Hmm, I'd like to answer my question... :)

buyers=purchases.project(:buyer_id).group(purchases[:buyer_id]) #<-- all buyers
busers=users.where(users[:id].in(buyers))  #<--answer

OTHER TIPS

The Rails Guide has really good documentation for ARel.

http://guides.rubyonrails.org/active_record_querying.html#conditions

The Rails API is also pretty useful for some of the more obscure options. I just google a specific term with "rails api" and it comes up first.

I don't believe that the code above issues a nested query. Instead, it appears that it would issue 2 separate SQL queries. You may have comparable speed (depending on how concerned you are with performance), but with 2 round trips to the server, it doesn't offer the same benefits of nested queries.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top