如何检查验证是否为真并在控制器中的条件下使用它?
模型
validate :no_reservation_overlap
scope :overlapping, ->(period_start, period_end) do
where "((date_start <= ?) and (date_end >= ?))", period_end, period_start
end
private
def no_reservation_overlap
if (Reservation.overlapping(date_start, date_end).any?)
errors.add(:date_end, 'it overlaps another reservation')
end
end
链接了解更多信息:Date range overlap per user rails
我希望能够检查验证是否为真并将其传递给控制器
控制器
if validation == true
#do something
end
我尝试使用on: create
来阻止它执行create
操作。
答案 0 :(得分:5)
只需在ActiveRecord对象上调用valid?
即可。例如:
@reservation = Reservation.new(reservation_params)
if @reservation.valid?
# Do something if any validation fails
if @reservation.errors[:date_end].include? 'it overlaps another reservation'
# Do something if the overlapping validation fails
end
end
中详细了解有关验证的信息
如果您想检查特定的验证错误,可以查看this Stack Overflow question。
答案 1 :(得分:1)
if @user.valid?
do something
end