我有一个记录user_id,guest_ip和timestamps的个人资料视图模型。
>> @user.profileviews
=> #<ActiveRecord::Associations::CollectionProxy [#<Profileview id: 3, guest_ip: "127.0.0.1", user_id: 8, created_at: "2014-03-09 17:38:00", updated_at: "2014-03-09 17:38:00">, #<Profileview id: 4, guest_ip: "127.0.0.1", user_id: 8, created_at: "2014-03-09 17:40:04", updated_at: "2014-03-09 17:40:04">, #<Profileview id: 5, guest_ip: "127.0.0.1", user_id: 8, created_at: "2014-03-09 17:40:10", updated_at: "2014-03-09 17:40:10">, #<Profileview id: 9, guest_ip: "127.0.0.1", user_id: 8, created_at: "2014-03-09 17:41:44", updated_at: "2014-03-09 17:41:44">, #<Profileview id: 10, guest_ip: "127.0.0.1", user_id: 8, created_at: "2014-03-09 17:45:39", updated_at: "2014-03-09 17:45:39">, #<Profileview id: 11, guest_ip: "127.0.0.1", user_id: 8, created_at: "2014-03-09 17:46:29", updated_at: "2014-03-09 17:46:29">, #<Profileview id: 12, guest_ip: "127.0.0.1", user_id: 8, created_at: "2014-03-09 17:47:00", updated_at: "2014-03-09 17:47:00">, #<Profileview id: 15, guest_ip: "127.0.0.1", user_id: 8, created_at: "2014-03-09 17:53:01", updated_at: "2014-03-09 17:53:01">]>
此(@ user.profileviews)返回记录在用户配置文件中的ActiveRecord配置文件视图数组。现在我想查看@user.provileviews.count
可以完成的视图计数。然后我想提取uniq视图。
我尝试使用@ user.profileviews.uniq.count来做到这一点。当然不起作用,因为单一性只能依据IP。我在Ruby on Rails API上找到了this。我做了类似的事情,显然不起作用:@userviews = @user.profileviews.uniq_by { |i| i.uniq? }
有任何线索如何让它发挥作用?或者任何其他方式/想法来获得独特的(通过IP)视图?
答案 0 :(得分:2)
如果给出块,它将使用块的返回值进行比较。它使用
hash
和eql?
方法比较值以提高效率。
@user.profileviews.uniq { |i| i.guest_ip }
@user.profileviews.uniq(&:guest_ip)
答案 1 :(得分:2)
也许你想看看ActiveRecord::Calculations#count
。当你做类似的事情时:
@user.profileviews.group(:guest_ip).count
# => { '2.3.4.5' => 5, '1.2.3.4' => 3, ...}
您获得了一个由ip分组的综合浏览量的哈希值。因此,只需对数据库进行一次查询,即可获得唯一的综合浏览量(散列键数)和所有综合浏览量(值的总和)。