Last active
October 8, 2017 21:01
-
-
Save vlado/db6c774d3e0d01ba780995b8dd6ca86b to your computer and use it in GitHub Desktop.
Rails bug when creating using association and scopes?
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Appointment < ApplicationRecord | |
belongs_to :inquiry | |
enum appointment_type: { default: 0, q1: 1, q2: 2 } | |
scope :q1, -> { where(appointment_type: q1) } | |
scope :on_date, -> (date) { where(scheduled_date: date) } | |
before_validation :set_start_and_end_time | |
def duration | |
[15, 30, 45].sample | |
end | |
private | |
def set_start_and_end_time | |
self.start_time = if last_appointment_on_same_date = Appointment.on_date(scheduled_date).last | |
last_appointment_on_same_date.end_time | |
else | |
scheduled_date.in_time_zone.change(hour: 8) # 08:00 on scheduled_date | |
end | |
self.end_time = self.start_time + duration | |
end | |
end |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# app/models/inquiry.rb | |
class Inquiry < ApplicationRecord | |
has_many :appointments | |
end |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
inquiry_params: { description: "Test inquiry" } | |
appointment_params: { scheduled_date: Time.zone.today } | |
@inquiry = Inquiry.new(inquiry_params) | |
@inquiry.transaction do | |
@inquiry.save! | |
# This does not work cause check for last appointment in `set_start_and_end_time` before validation hook will ne scoped with | |
# inquiry id and q1 appointment type. | |
# `Appointment.on_date(scheduled_date).last` will produce following SQL: | |
# SELECT * FROM appointments WHERE scheduled_date = 2017-10-08 AND inquiry_id = 12345 AND appointment_type = q1 ORDER BY id DESC LIMIT 1 | |
# @inquiry.appointments.q1.create!(appointment_params) | |
# This will work ok. | |
# `Appointment.on_date(scheduled_date).last` will produce following SQL: | |
# SELECT * FROM appointments WHERE scheduled_date = 2017-10-08 ORDER BY id DESC LIMIT 1 | |
appointment = @inquiry.appointment.q1.new(appointment_params) | |
appointment.save! | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment