ruby-on-rails – 带有连接和顺序的独特记录

前端之家收集整理的这篇文章主要介绍了ruby-on-rails – 带有连接和顺序的独特记录前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我在用户和捐赠之间有一个简单的关系,即用户有很多捐赠,捐赠属于用户.我想做的是获取最近捐赠的用户列表. @H_403_2@这是我正在尝试的:

@H_403_2@首先,我想获得uniq用户的总数,这是按预期工作的:

> User.joins(:donations).order('donations.created_at').uniq.count
   (3.2ms)  SELECT DISTINCT COUNT(DISTINCT "users"."id") FROM "users" INNER JOIN "donations" ON "donations"."user_id" = "users"."id"
 => 384
@H_403_2@接下来,当我删除count方法时,出现“ORDER BY表达式必须出现在选择列表中”的错误

> User.joins(:donations).order('donations.created_at').uniq
  User Load (0.9ms)  SELECT DISTINCT "users".* FROM "users" INNER JOIN "donations" ON "donations"."user_id" = "users"."id" ORDER BY donations.created_at
PG::InvalidColumnReference: ERROR:  for SELECT DISTINCT,ORDER BY expressions must appear in select list
LINE 1: ...ON "donations"."user_id" = "users"."id"  ORDER BY donations....
@H_403_2@然后我尝试通过显式设置SELECT子句来修复Postgres错误,该子句乍一看似乎有效:

> User.select('DISTINCT "users".id,"users".*,"donations".created_at').joins(:donations).order('donations.created_at')
  User Load (17.6ms)  SELECT DISTINCT "users".id,"donations".created_at FROM "users" INNER JOIN "donations" ON "donations"."user_id" = "users"."id" ORDER BY donations.created_at
@H_403_2@但是,返回的记录数不考虑DISTINCT语句并返回692条记录:

> _.size
 => 692
@H_403_2@如何根据捐赠的created_at时间戳排序,获得预期的结果数(384)?

解决方法

试试这个:
User.select('users.*,MAX(donations.created_at) as most_recent_donation').
  joins(:donations).order('most_recent_donation desc').group('users.id')
@H_403_2@我想用户有很多捐款,这将选择最近创建的捐款,并选择按其ID过滤的不同用户.

@H_403_2@我没有测试过这个.

猜你在找的Ruby相关文章