Rails:找到少于X关联的模型,也包括没有任何关联的模型(Rails: Find model with less than X associations, also including the ones without any)

我正试图让我们的用户分组。

用户型号:

Class User has_many :orders

订购型号:

Class Order has_many :orders

现在让我们说,我想让一小部分用户的订单少于5个。

User .joins('left outer join orders on users.id = orders.user_id') .group(:user_id) .having('count(user_id) <= ?' 5)

但是,这只会吸引至少有一个订单的用户。 我还需要做些什么来包括没有任何订单的用户?

I'm trying to make a way to group our users into segments.

User model:

Class User has_many :orders

Order model:

Class Order has_many :orders

Now let's say that I want to make a segment of users who have made less than 5 orders.

User .joins('left outer join orders on users.id = orders.user_id') .group(:user_id) .having('count(user_id) <= ?' 5)

However this just grabs the users that have at least 1 order. What do I need to do to also include users who don't have any orders?

最满意答案

我没有测试过,所以试试这个,让我知道。

User.joins( :orders ).group( 'users.id' ).having( 'count( order_id ) < 5' )

我相信你正在计算错误的列。 你应该计数order_id 。 随意评论,如果我错了,或者如果这引发任何错误。

Figured it out myself. "eager_load" includes everything.

User.eager_load(:orders).group("users.id").having("count(orders.id) >= ?", 5)

Rails:找到少于X关联的模型,也包括没有任何关联的模型(Rails: Find model with less than X associations, also including the ones without any)

我正试图让我们的用户分组。

用户型号:

Class User has_many :orders

订购型号:

Class Order has_many :orders

现在让我们说,我想让一小部分用户的订单少于5个。

User .joins('left outer join orders on users.id = orders.user_id') .group(:user_id) .having('count(user_id) <= ?' 5)

但是,这只会吸引至少有一个订单的用户。 我还需要做些什么来包括没有任何订单的用户?

I'm trying to make a way to group our users into segments.

User model:

Class User has_many :orders

Order model:

Class Order has_many :orders

Now let's say that I want to make a segment of users who have made less than 5 orders.

User .joins('left outer join orders on users.id = orders.user_id') .group(:user_id) .having('count(user_id) <= ?' 5)

However this just grabs the users that have at least 1 order. What do I need to do to also include users who don't have any orders?

最满意答案

我没有测试过,所以试试这个,让我知道。

User.joins( :orders ).group( 'users.id' ).having( 'count( order_id ) < 5' )

我相信你正在计算错误的列。 你应该计数order_id 。 随意评论,如果我错了,或者如果这引发任何错误。

Figured it out myself. "eager_load" includes everything.

User.eager_load(:orders).group("users.id").having("count(orders.id) >= ?", 5)