2

I started code rails recently and I need to figure out this problem.

%td
  =  Ahoy::Event.where(name: "viewed_brochure").where_properties(brochure_id: brochure.id).select(:session_id).uniq

This should find number of distinct values of session_id in properties field but it doesn't work.

This line returns these and similar errors

#<Ahoy::Event::ActiveRecord_Relation:0x007f52d9325130>
#<Ahoy::Event::ActiveRecord_Relation:0x007f52d9466508>

%td
  =  Ahoy::Event.select { |event| event.properties['session_id'] }.uniq.count

I tried this line but this time returns number of rows in table

Emre
  • 119
  • 2
  • 8
  • how `event` and `properties` are associated? – Anand Nov 07 '17 at 13:14
  • I use ahoy gem. So i have ahoy_events table and this table contains properties field. Generally ahoy queries use where_properties function find data. Btw properties field contains session_id. – Emre Nov 07 '17 at 13:22
  • what errors are you facing? – Anand Nov 07 '17 at 13:29
  • 1
    http://guides.rubyonrails.org/active_record_basics.html – Jared Beck Nov 07 '17 at 14:32
  • What is the data type of properties attribute? Hstore or jsonb? – Anton Nov 08 '17 at 07:54
  • data type of properties is jsonb @Anton – Emre Nov 08 '17 at 08:28
  • I don't currently have a model with jsonb to test on.. can you try: Ahoy::Event.group("properties -> 'session_id'").count OR @> instead of -> – Anton Nov 08 '17 at 09:45
  • this is so close to figure out the problem your solution is return like these {"98d2c824477ee292507d7a28bce8a4a0"=>1, "ebbe52f15133dc3ce1b55a9acfdad98c"=>2} I need to convert to number. This case must return 2. – Emre Nov 08 '17 at 10:43
  • @Emre, I'll make it an answer. Can you accept it? – Anton Nov 08 '17 at 11:29

2 Answers2

2

You can try to group by jsonb key, in your case properties['session_id']

Ahoy::Event.group("properties -> 'session_id'").count

This will return the counts on which you can apply .size or you could do distinct.

Anton
  • 540
  • 3
  • 13
0

Thank u so much @Anton I modify your solution and finally it works fine.

Here is the solution

%td
  =  Ahoy::Event.where_properties(brochure_id: brochure.id).group("properties -> 'session_id'").count.size
Emre
  • 119
  • 2
  • 8