2013-05-15 45 views
0

以下代碼正在工作,並且Customer#number_appointments_in_month可正確返回特定月份內的約會數量。獲取滿足兩級深層關係標準的對象數量

但是,我覺得我沒有使用Rails功能。我應該使用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