自定义验证未在创建记录时执行?

时间:2019-03-25 15:51:10

标签: ruby-on-rails ruby

我的自定义验证存在问题,未验证表单上的日期字段。我的目的是在数据库中搜索约会记录中当前用户的现有日期。但是,当我将日期更改为已经采用的日期时,我的验证就不会生效。我一定把它设置错了,任何帮助将不胜感激!

class AppointmentsController < ApplicationController
  before_action :set_appointment, only: [:show, :edit, :update, 
:destroy]
  before_action :validate_schedule, :before => :create

  private
     def validate_schedule
        if Appointment.where(date: params[:date], user: current_user).exists?
            flash[:notice] = "You already have a date in this time"
        else
            flash[:notice] = "No conflicts"
     end
 end
end

_form.html.erb

<%= simple_form_for(@appointment) do |f| %>
  <%= f.error_notification %>
  <%= f.error_notification message: f.object.errors[:base].to_sentence if f.object.errors[:base].present? %>

  <!-- Show only patients to the current logged in users -->
  <div class="form-inputs">
    <%= f.input :notes %>
    <%= f.input :date %>
    <%= f.association :patient, label_method: :Full_Name, :collection => Patient.where(:user => current_user.id) %>
  </div>

  <div class="form-actions">
      <div style="display: flex; float: left;">
          <%= link_to 'Back', appointments_path, class: "btn btn-warning btn-m"%>
      </div>
      <div style="display: flex; float: right;">
          <%= f.button :submit , class: "btn btn-success btn-m"%>
      </div>
  </div>

<% end %>

1 个答案:

答案 0 :(得分:1)

这看起来很像模型验证:

class Appointment
  validates :date, uniqueness: { scope: :user }