简体   繁体   中英

Custom validation not executing on creation of record?

I having an issue with my custom validation not validating a the date field on my form.My aim is to search the database for an existing date for the current user in appointment records.The flash notification appears when I go to the creation of the record however when i change the date to one that is already taken my validation does not pick this up. I must be setting it up wrong, any help would be greatly appreciated!

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 %>

This looks a lot like a model validation:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM