For the sake of simplifying my problem, let’s say we have three models; user, flight, and plane. I want to show a table to the user of how many times they have flown each plane they’ve flown.
I am completely stuck as to how to achieve this… the most simple solution I could think of is to loop through the flights like so…
flown_planes = {}
@user.flights.each do |f|
if flown_planes[f.plane.id]
flown_planes[f.plane.id] += 1
else
flown_planes[f.plane.id] = 1
end
end
Can I somehow use .find and .count to achieve this? I’m sure there is a much cleaner way than above. Please see the relationships below.
Flight
class Flight < ActiveRecord::Base
belongs_to :user
belongs_to :plane
end
Plane
class Plane < ActiveRecord::Base
has_many :flights
end
User
class User < ActiveRecord::Base
has_many :flights
end
Use
group_byto group the flights of the user by the planes!That should do it for you,…
// For iteration…