Ruby on rails 获取两级深度关系中满足条件的对象数

Ruby on rails 获取两级深度关系中满足条件的对象数,ruby-on-rails,ruby,ruby-on-rails-3,ruby-on-rails-3.2,Ruby On Rails,Ruby,Ruby On Rails 3,Ruby On Rails 3.2,以下代码正在运行,Customer#number_appointment_in_month正确返回特定月份内的约会次数 但是,我觉得我没有使用Rails功能。我应该使用SQL语句吗? 是否有一种更优雅的方式来编写客户#月约会次数 方法 class Calendar < ActiveRecord::Base has_many :appointments end class Appointment < ActiveRecord::Base # property 'start_d

以下代码正在运行,
Customer#number_appointment_in_month
正确返回特定月份内的约会次数

但是,我觉得我没有使用Rails功能。我应该使用SQL语句吗? 是否有一种更优雅的方式来编写
客户#月约会次数

方法

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 
class日历
我建议您在不同的模型之间分离关注点。 这个怎么样

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
class日历