user984621
user984621

Reputation: 48483

Ruby On Rails - what's the best way to find an object with most (has-many) associations?

I have a variable (@cars) containing data from the database and from here, I need to generate an XLS document.

Because of some specifics of the XLS document, I need to know in advance the length of some associations (model Car has a has_many association for the model PreviousOwner) - particularly, I need to know how many previous owners each car had and I need to capture the highest number of previous owners of all cars.

One way of finding that is adding counter_cache to the Car model structure, is there any other way to deal with this situation? I have @cars variable and from there I need to find the car with the most previous owners.

Upvotes: 1

Views: 589

Answers (1)

max
max

Reputation: 102240

One of the ways of dealing with it is by joining and selecting a count:

Car.left_joins(:previous_owners)
   .select(
     'cars.*', 
     'COUNT(previous_owners.*) AS previous_owners_count'
   )
   .group(:id)
   .order(previous_owners_count: :desc)

Advantages when compared to a counter cache:

  • No additional update queries when inserting associated records.
  • More accurate if the count is critical and you have a lot of write activity.

Disadvantages:

  • Count is calculated for every query which is less efficient when reading.
  • It gets in the way of eager loading the records.
  • More code complexity vs a simple model callback.

Upvotes: 3

Related Questions