0

I need to create a new datetime record in my database but first I need to find out is there the same date already saved. The dates inside my database add 4 hours. So, when there is a date which shows it's 2pm, the same date inside database will show it's 6pm. If the dates are the same an alert windows should show.

I'm trying to do something like this but I am not completely sure am I going into right direction:

        def create
        @appointment_new = Appointment.new(:start_date => params[:start_date], 
            :end_date => params[:end_date], :doctor_id => params[:doctor_id], 
            :user_id => params[:user_id])

        @appointments = Appointment.all

        hour = appointment_new.start_date.hour
        minute = appointment_new.start_date.minute

        check = false

        @appointments.each do |appointment|
        {
                ?????????????
        }
        end

        if(check)
            {
                if @appointment.save
                    flash[:success] = "Welcome!"
                    redirect_to @user
                else
                    alert("failure!")
                end
            }
            else
                 // do something
    end

What do you think? Thanks!

1 Answer 1

2

In your Appointment model, can start_date be a key? Then you can have this callback:

before_validation(on: :create) do
    self.start_date = start_date + 4.hours if attribute_present?("start_date")
end

Then the model will fail to save because of a duplicate key.

Not sure how your model is structured, but just a thought.

Sign up to request clarification or add additional context in comments.

1 Comment

Or just try to save the record and trap any duplicate key exception. That'd be one hit on the database instead of a lookup followed by an insert if the lookup failed.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.