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 
4

1 回答 1

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
于 2013-05-15T22:18:41.950 回答