开发者

Nested queries using Arel (Rails3)

开发者 https://www.devze.com 2023-01-23 21:28 出处:网络
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.

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`开发者_Go百科 IN (SELECT DISTINCT `buyer_id` FROM  `purchases`)

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


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


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消