Search code examples
ruby-on-railsactiverecordmodelrelationships

Rails - Multiple Relationship Find


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

Solution

  • Use group_by to group the flights of the user by the planes!

    @user.flights.group_by(&:plane_id)
    

    That should do it for you,...

    // For iteration...

    @user.flights.group_by(&:plane_id).each do |plane_id, flights|
         plane = Plane.find(plane_id) # gives you the plain object so you can fetch the plane name/identification,... whatever you need
         flights.count # gives you count of flights in the plane
         flights.each do |flight|
              # do anything if you want with each of the flights the user had...
         end
    end