以下代码正在运行并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