2011-11-18 2 views
1

내 문제를 단순화하기 위해 세 가지 모델이 있다고 가정 해 보겠습니다. user, flightplane. 나는 그들이 비행 한 각 비행기를 몇 번이나 비행했는지에 대한 표를 사용자에게 보여주고 싶다.레일 - 복수 관계 찾기

나는

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 

은 어떻게 든 사용할 수 있습니다 ... 내가 지금과 같은 항공편을 반복하는 것입니다 생각할 수있는이 ... 가장 간단한 솔루션을 달성하는 방법에 관해서는 완전히 붙어 오전 .find.count 이것을 달성하기 위해? 위의 방법보다 훨씬 깨끗한 방법이 있다고 확신합니다. 아래의 관계를 참조하십시오.


비행

class Flight < ActiveRecord::Base 
    belongs_to :user 
    belongs_to :plane 
end 

비행기

class Plane < ActiveRecord::Base 
    has_many :flights 
end 

사용자

class User < ActiveRecord::Base 
    has_many :flights 
end 

답변

1

group_by을 사용하여 비행기로 사용자의 비행을 그룹화하십시오!

@user.flights.group_by(&:plane_id) 
당신을 위해 무엇을해야

, ...

// 반복을 위해 ...

@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 
+0

확인 감사합니다 -하지만 난 그들로부터 루프해야하고, 루프 I에서 비행기 객체를 가져야하고, 사용자가 그 비행기를 몇 번이나 탔는지의 횟수 - 어떻게하면 될까요? –

+0

게시물의 업데이트를 참조하십시오 – davidb

+0

오늘 두 번째 질문에 대해 당신이 대답했습니다. :) –