Ruby on Rails 3 - 自定义日期验证



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

这是我的表计划架构

  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为真,则可以创建记录,否则会引发错误。

有没有办法循环访问表计划的数据字段以评估哪些天返回 true 或 false,以便我可以将其与请求的日期进行比较?

我想你可能正在寻找这样的东西。假设您正在尝试验证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

相关内容

  • 没有找到相关文章

最新更新