2013-05-15 2 views
0

다음 코드는 작동하며 Customer#number_appointments_in_month은 특정 달 내에 약속 수를 올바르게 반환합니다.두 수준의 깊은 관계로 조건을 만족하는 개체 수 얻기

그러나 레일스 기능을 사용하지 않는 것 같습니다. 오히려 SQL 문을 사용해야합니까? Customer#number_appointments_in_month을 작성하는 좀 더 우아한 방법이 있습니까?

방법

class Calendar < ActiveRecord::Base 
    has_many :appointments 
end 

class Appointment < ActiveRecord::Base 
    # property 'start_date' returns a DateTime 
end 

class Customer < ActiveRecord::Base 
    has_many :calendar 

    def number_appointments_in_month(month = Date.today.month, year = Date.today.year) 
    calendar.sum do |cal| 
     apps = cal.appointments.select do |app| 
     year == app.start_date.year && month == app.start_date.month 
     end 
     apps.size 
    end # calendars.sum 
    end 
end 

답변

1

내가 당신에게 당신의 다른 모델 사이에 우려의 일부 분리를 제안한다. 어때요?

class Calendar < ActiveRecord::Base 
    has_many :appointments 
    def appointments_in_month month, year 
    self.appointments.select do |app| 
     app.in? month, year 
    end 
    app.length 
    end 
end 

class Appointment < ActiveRecord::Base 
    def in? month, year 
    year == self.start_date.year && month == self.start_date.month 
    end 
end 

class Customer < ActiveRecord::Base 
    has_many :calendar 
    def number_appointments_in_month month, year 
    self.calendars.reduce(0) do |total,c| 
     total + c.appointments_in_month(month, year) 
    end 
    end 
end 
관련 문제