Reputation: 48483
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
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:
Disadvantages:
Upvotes: 3