从两个数组中选择一组唯一的activerecord对象

时间:2014-12-03 02:35:43

标签: ruby-on-rails ruby

我有两个查询在我的应用中返回用户记录,它们如下所示:

alert_queue = scope(alert.player_id)    
all_queue = User.where(all_alerts: 1)

scope方法和显然User.where都返回用户记录。

我的问题是,无论如何,我可以合并这两个数组,只获得唯一的用户记录。如果我按原样合并数组,则可能会为上面的每个查询返回相同的用户并列出两次。我想让它们与众不同。

1 个答案:

答案 0 :(得分:1)

您可以简单地将数组加在一起并在其上调用uniq,如下所示:

(alert_queue + all_queue).uniq

这是一个展示ActiveRecord示例的示例应用程序:

2.1.1 :014 > jeff = User.where(name: 'jeff')
  User Load (0.6ms)  SELECT "users".* FROM "users"  WHERE "users"."name" = 'jeff'
 => #<ActiveRecord::Relation [#<User id: 6, name: "jeff", alert: 5, created_at: "2014-12-03 02:50:32", updated_at: "2014-12-03 03:03:43">]>
2.1.1 :015 > alerts = User.where(alert: 5)
  User Load (0.6ms)  SELECT "users".* FROM "users"  WHERE "users"."alert" = 5
 => #<ActiveRecord::Relation [#<User id: 1, name: nil, alert: 5, created_at: "2014-12-03 02:50:11", updated_at: "2014-12-03 02:50:11">, #<User id: 2, name: nil, alert: 5, created_at: "2014-12-03 02:50:11", updated_at: "2014-12-03 02:50:11">, #<User id: 3, name: nil, alert: 5, created_at: "2014-12-03 02:50:11", updated_at: "2014-12-03 02:50:11">, #<User id: 4, name: nil, alert: 5, created_at: "2014-12-03 02:50:11", updated_at: "2014-12-03 02:50:11">, #<User id: 5, name: nil, alert: 5, created_at: "2014-12-03 02:50:11", updated_at: "2014-12-03 02:50:11">, #<User id: 6, name: "jeff", alert: 5, created_at: "2014-12-03 02:50:32", updated_at: "2014-12-03 03:03:43">]>
2.1.1 :016 > jeff.count
   (0.7ms)  SELECT COUNT(*) FROM "users"  WHERE "users"."name" = 'jeff'
 => 1
2.1.1 :017 > alerts.count
   (0.7ms)  SELECT COUNT(*) FROM "users"  WHERE "users"."alert" = 5
 => 6
2.1.1 :018 > (jeff + alerts).uniq.count
 => 6
2.1.1 :019 > (jeff + alerts).uniq
 => [#<User id: 6, name: "jeff", alert: 5, created_at: "2014-12-03 02:50:32", updated_at: "2014-12-03 03:03:43">, #<User id: 1, name: nil, alert: 5, created_at: "2014-12-03 02:50:11", updated_at: "2014-12-03 02:50:11">, #<User id: 2, name: nil, alert: 5, created_at: "2014-12-03 02:50:11", updated_at: "2014-12-03 02:50:11">, #<User id: 3, name: nil, alert: 5, created_at: "2014-12-03 02:50:11", updated_at: "2014-12-03 02:50:11">, #<User id: 4, name: nil, alert: 5, created_at: "2014-12-03 02:50:11", updated_at: "2014-12-03 02:50:11">, #<User id: 5, name: nil, alert: 5, created_at: "2014-12-03 02:50:11", updated_at: "2014-12-03 02:50:11">]