PublicActivity:获取所有用户的独特活动

时间:2014-09-05 19:36:20

标签: ruby-on-rails activerecord distinct public-activity

我正在使用Public Activity gem来跟踪用户的评论。我想在查询中获取所有唯一用户注释。我尝试了以下操作:

PublicActivity::Activity.where(:trackable_type=>"Comment").where(:owner_id => user.id).all.select(:trackable_id).distinct

但是我收到了错误:

ArgumentError: wrong number of arguments(1 for 0)
    from (irb):14:in `select'
    from (irb):14
    from /Users/ttseng/.rvm/gems/ruby-1.9.3-p448/gems/railties-3.2.15/lib/rails/commands/console.rb:47:in `start'
    from /Users/ttseng/.rvm/gems/ruby-1.9.3-p448/gems/railties-3.2.15/lib/rails/commands/console.rb:8:in `start'
    from /Users/ttseng/.rvm/gems/ruby-1.9.3-p448/gems/railties-3.2.15/lib/rails/commands.rb:41:in `<top (required)>'
    from script/rails:6:in `require'
    from script/rails:6:in `<main>'

是否有人知道如何根据trackable_id提取用户的唯一活动?

作为参考,这是我尝试获取唯一记录之前查询结果的样子:

enter image description here

2 个答案:

答案 0 :(得分:2)

我在Rails控制台上做了以下操作,看看我得到了什么

 2.0.0p353 :020 > PublicActivity::Activity.where(id:1).class
 => ActiveRecord::Relation::ActiveRecord_Relation_PublicActivity_Activity 
2.0.0p353 :021 > PublicActivity::Activity.all.class
 => ActiveRecord::Relation::ActiveRecord_Relation_PublicActivity_Activity 
2.0.0p353 :022 > PublicActivity::Activity.where(id:1).all.class
DEPRECATION WARNING: Relation#all is deprecated. If you want to eager-load a relation, you can call #load (e.g. `Post.where(published: true).load`). If you want to get an array of records from a relation, you can call #to_a (e.g. `Post.where(published: true).to_a`). (called from irb_binding at (irb):22)
W, [2014-09-06T01:47:09.341145 #8594]  WARN -- : DEPRECATION WARNING: Relation#all is deprecated. If you want to eager-load a relation, you can call #load (e.g. `Post.where(published: true).load`). If you want to get an array of records from a relation, you can call #to_a (e.g. `Post.where(published: true).to_a`). (called from irb_binding at (irb):22)
  PublicActivity::Activity Load (0.6ms)  SELECT "activities".* FROM "activities" WHERE "activities"."id" = 1
D, [2014-09-06T01:47:09.343063 #8594] DEBUG -- :   PublicActivity::Activity Load (0.6ms)  SELECT "activities".* FROM "activities" WHERE "activities"."id" = 1
 => Array 
2.0.0p353 :023 > 

正如您所看到的,您正在数组上执行选择操作,这就是为什么您会收到此类错误ArgumentError: wrong number of arguments(1 for 0)

试试这个,

 PublicActivity::Activity.where(:trackable_type=>"Comment").where(:owner_id => user.id).select(:trackable_id).distinct

答案 1 :(得分:0)

答案是运行以​​下内容:

PublicActivity :: Activity.where(:trackable_type =&gt;&#34; Comment&#34;)。where(:owner_id =&gt; user.id).select(&#34; DISTINCT ON(trackable_id)*& #34)