0

In Rails 7:

I have an Object which has many Associations.

Associations have a :start_time datetime attribute.

I want to return Objects, ranked in order by number of Associations over a certain period of time.

I have tried:

  1. creating an array of Associations from date1 to date2
  2. using group_by and each with object to create a hash of Object.ids and frequencies

but I cannot figure out how to rank them by frequency.

I also think their is an easier way to do this.

I am sure this will get downvoted for lack of detail/code, but the question is very general and the use case common.

Any suggestion is appreciated.

user2799827
  • 1,077
  • 3
  • 18
  • 54

1 Answers1

1

In case anyone else is looking.

Essentially I did something akin to the following:

in the Association model:

  def self.grouped
    exclusionId = Object.find_by(name: 'Excluded Object').id
    Association.joins(:object).where.not(object_id: exclusionId)                                                                                   .group_by{|assoc| assoc.object_id}
  end

  def self.ranked_objects
    association_by_object = Association.grouped.each_with_object({}) { |(k,v),h| h[k] = v.size }
    (association_by_object.sort_by{|key, value| value}).reverse
  end

Then in the applicable controller action:

  def objects_ranked
    render json: Association.ranked_objects.to_json
  end
user2799827
  • 1,077
  • 3
  • 18
  • 54