我需要确保每个日期只能有一个房间的房间。
这是我的逻辑。
如果一天没有房间的SKU =>好 如果一天只有一个房间的一个SKU,那么检查sku是否等于它自己。 如果是这样=>好 如果不是=>失败
我认为我的逻辑不是那么强大且难以理解。
我打赌在RoR上有一个很好的解决方案。
class RoomSku < ActiveRecord::Base
belongs_to :room
validate :should_be_unique_in_one_day
def should_be_unique_in_one_day
skus_on_this_day = _get_skus_on_this_day
if skus_on_this_day.count==0
nil
elsif skus_on_this_day.count==1 and skus_on_this_day.first.id = self.id
nil
else
errors.add(:departure_at, I18n.t("already_exists_on_the_same_day"))
end
end
def _get_skus_on_this_day
self.class.where(room_id: self.room_id, date: self.date)
end
end
答案 0 :(得分:2)
我相信您正在寻找的是范围内的唯一性验证
validates :date, uniqueness: { scope: :room_id }
或者,如果必须将错误应用于departure_at
,您可以执行以下操作:
def should_be_unique_in_one_day
errors.add(:departure_at, I18n.t("already_exists_on_the_same_day")) if RoomSku.where(room_id: room_id, date: date).where.not(id: id).exists?
end