Date range overlap per user rails

后端 未结 1 1263
既然无缘
既然无缘 2021-01-16 06:18

How can I make the validation of the date per user using the code below? When I logged in as a different user I am not able to create a reservation with the same dates. I ha

相关标签:
1条回答
  • 2021-01-16 06:35

    Guess you could try to add this to your validate:

    validate :no_reservation_overlap, :uniqueness => { :scope => :user_id }
    

    Not sure if this works for you cause, but you should give it a try. Good luck!

    EDIT:

    I would suggest a different approach:

    validate :no_reservation_overlap
    
    
    def no_reservation_overlap
      if (Reservation.where("(? BETWEEN date_start AND date_end OR ? BETWEEN date_start AND date_end) AND user_id = ?", self.date_start, self.date_end, self.user_id).any?)
         errors.add(:date_end, 'it overlaps another reservation')
      end
    end
    

    Guess this should work, please give it a try

    0 讨论(0)
提交回复
热议问题