Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/reporting-services/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby on rails 如何验证更新的开始日期?_Ruby On Rails_Ruby On Rails 3_Validation - Fatal编程技术网

Ruby on rails 如何验证更新的开始日期?

Ruby on rails 如何验证更新的开始日期?,ruby-on-rails,ruby-on-rails-3,validation,Ruby On Rails,Ruby On Rails 3,Validation,如何验证更新时的开始日期,使其不应是以前保存的日期之前的日期。 例如:-就像我创建的记录,开始日期为2013年11月7日,更新时不应早于2013年11月7日 鉴于: f.input :start_date, as: :datepicker f.input :end_date, as: :datepicker 型号: validates :start_date, allow_nil: true, date: { after: Date.today - 1, message: 'must be t

如何验证更新时的开始日期,使其不应是以前保存的日期之前的日期。 例如:-就像我创建的记录,开始日期为2013年11月7日,更新时不应早于2013年11月7日

鉴于:

f.input :start_date, as: :datepicker
f.input :end_date, as: :datepicker
型号:

validates :start_date, allow_nil: true, date: { after: Date.today - 1, message: 'must be today or after today' }, on: :create
validates :end_date, allow_nil: true, date: { after: :start_date, message: 'must be after start date' }

谢谢。

我现在无法测试它,但我认为它可能会起作用:

validate :previous_start_date

def previous_start_date
  old_start_date = Model.find(self.id).start_date
  if(old_start_date > self.start_date)
   self.errors.add(:start_date, "Can't be previous than the initial date")
  end 
end
在验证的时候,对象还没有被保存,所以,我相信从数据库中检索对象会得到之前的值。使用手头的值,您可以与当前开始日期进行比较,然后添加自定义错误


我希望这会有所帮助。

您可以添加属性访问器:上一个开始日期(也不要忘记属性可访问)以及在表单上添加隐藏字段。此字段的值必须等于从DB开始的开始日期。 然后可以使用after:previous\u start\u date。
注意:值previous\u start\u date必须从DB中设置,最好在getter方法的模型中设置,或者在验证回调之前设置。

谢谢@Andre。但是应该是“验证:上一个开始日期”,因为“验证”用于属性,“验证”用于自定义验证。哦,谢谢@user2788206我编辑了答案:)它对你有用吗?如果是,你能接受答案吗?