0

我正在尝试创建一个自定义验证来评估创建记录所请求的日期是否可用。

这是我的表计划架构

  create_table "schedules", :force => true do |t|
    t.datetime "created_at", :null => false
    t.datetime "updated_at", :null => false
    t.integer  "doctor_id"
    t.boolean  "sun"
    t.boolean  "mon"
    t.boolean  "tue"
    t.boolean  "wed"
    t.boolean  "thu"
    t.boolean  "fri"
    t.boolean  "sat"
  end

例如,如果请求的日期是星期五并且schedule.fri为真,则可以创建记录,否则会引发错误。

有没有办法遍历表计划的数据字段来评估哪些天返回真或假,以便我可以将它与请求的日期进行比较?

4

1 回答 1

0

我想你可能正在寻找这样的东西。假设您正在尝试验证Appointment模型,验证可能类似于:

class Appointment
  # this assumes that the appointment has at least two fields:
  # doctor_id : the same value as in the Schedule object
  # adate : a string in the form "mon", "tue", etc.
  validate :doctor_is_free
  def doctor_is_free 
    schedule = Schedule.where(doctor_id: self.doctor_id).first
    #return the day of a date. e.g. "sun"
    requested_day = adate.to_date.strftime("%a").downcase

    # this line will send a request to the Schedule instance using
    # the value of adate as the method name. So if adate == 'tue' and
    # schedule.tue = false then this will add an error to the validation.
    unless schedule.send(requested_day.to_sym)
      self.errors[:adate] << "The doctor is not available on #{ self.adate }"
    end
  end
end
于 2013-01-25T17:08:19.380 回答