Answer the question
In order to leave comments, you need to log in
What is the best way to refactor?
class Reservation < ActiveRecord::Base
validates :table, presence: true
validates :start, presence: true
validates :finish, presence: true
validate :checking_the_time, :uniqueness_reservation
scope :tables, ->(table) { where("'reservations'.'table' = ? ", table) }
def checking_the_time
if start >= finish
errors.add(:finish, "Invalid time range")
end
end
def uniqueness_reservation
unless Reservation.diapazone(start, finish).tables(table).where.not(id: id).empty?
errors.add(:booked_from, 'Invalid period.')
end
end
private
def self.diapazone(start, finish)
where("(start >= :s AND finish <= :f) OR (start <= :s AND finish >= :s)
OR (start <= :f AND finish >= :f)",
{s: start, f: finish})
end
end
Answer the question
In order to leave comments, you need to log in
In general, programming is not done in machine codes for a long time. A little business logic wouldn't hurt b. What are tables? Do you rent an apartment and check that there is only one order in one time interval?
Then everything is easier
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question