我创建了一个模型:讲座(START_TIME,END_TIME,位置)。我想编写验证函数来检查新讲座的时间是否与数据库中保存的讲座重叠。这样我才能发现这个位置是否被占用。我的作用是:如何检查时间重叠轨道
class Lecture < ActiveRecord::Base
validates :title, :position, presence: true
validates :start_time, :end_time, format: { with: /([01][0-9]|2[0-3]):([0-5][0-9])/,
message: "Incorrect time format" }
validate: time_overlap
def time_overlap
Lecture.all.each do |user|
if (user.start_time - end_time) * (start_time - user.end_time) >= 0
errors.add(:Base, "time overlaps")
end
end
end
end
错误消息:NoMethodError在LecturesController#创建 未定义的方法` - 为无@”:NilClass。如何以正确的格式编写此功能?
你提到你在控制器中出现错误,但仍然没有添加控制器代码? – Alfie
您在'lectures_controller.rb'的'create'方法中有一个拼写错误(顺便说一下,您忽略了发布)。除此之外,你的时间冲突的方法是低效的。与使用数据库加载所有讲座并在Ruby中进行比较,最好使用start_time new_lecture.end_time构造一个选择讲座的查询。不要在应用程序代码中执行数据库可以为你做的事情。 –
MarsAtomic
控制器工作正常,没有time_overlap功能,我只是不明白什么是“未定义的方法' - @”的零。在此之际NilClass”我想我的代码在time_overlap有错红宝石风格希望能知道如何检查是否。时间与正确的代码重叠 – runchu