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