gpt4 book ai didi

ruby-on-rails - Rails 自定义验证有错误但仍在保存?

转载 作者:数据小太阳 更新时间:2023-10-29 08:49:43 24 4
gpt4 key购买 nike

我正在创建一个 Rails 应用程序来管理事件,我想添加验证以检查一个事件是否与另一个事件重叠。

这是我用于检查重叠事件的自定义验证代码:

class Event < ActiveRecord::Base
attr_accessible :full_date, :start_hour, :end_hour, :address

validate :no_overlapping_events

def no_overlapping_events
overlap = false
same_date = Event.where(:full_date => self.full_date).where("id != ?", self.id).where(:address => self.address)


same_date.each do |t|
if self.start_hour <= t.start_hour
if self.end_hour >= t.start_hour
overlap = true
break
end
end
end

if overlap == true
errors.add(:base, "Can't have overlapping events!")
end
end
end

我仍然可以创建重叠的事件,并且它们仍在保存中。我在这里做错了什么?

最佳答案

您的自定义验证方法“结束”得太早了。尝试:

class Event < ActiveRecord::Base
attr_accessible :full_date, :start_hour, :end_hour, :address

validate :no_overlapping_events

def no_overlapping_events
overlap = false
same_date = Event.where(:full_date => self.full_date).where("id != ?", self.id).where(:address => self.address)

same_date.each do |t|
if self.start_hour <= t.start_hour
if self.end_hour >= t.start_hour
overlap = true
break
end
end
end

if overlap == true
errors.add(:base, "Can't have overlapping events!")
end
end
end

此外,作为一个逻辑错误,如果出现以下情况怎么办:

self.start_hour > t.start_hour and self.start_hour < t.end_hour

关于ruby-on-rails - Rails 自定义验证有错误但仍在保存?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16160283/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com