我正在練習 Rails,我想知道如何驗證情況。
在這種情況下,它是一個汽車租賃專案。我有一張汽車(汽車)表和一個不可用期間。
注冊汽車時,我假設汽車在一個月內 100% 可用。如果有人在某個時期租用,它必須是不可用的,所以不能在同一時期再次租用,我將如何進行驗證?
模型
class UnavailablePeriod < ApplicationRecord
belongs_to :auto
end
class Auto < ApplicationRecord
belongs_to :rental_company
belongs_to :category
has_many :unavailable_periods
end
有什么建議嗎?內容提示學習這個?最好的方法是什么?
模型
uj5u.com熱心網友回復:
而不是一個UnavailablePeriod我會簡單地有一個Rental模型,它有一個rented_from和一個rented_until列(都是日期時間)。
在創建新的租賃時,您只需檢查是否沒有現有的、日期重疊的租賃。檢查您是否可以使用這樣的自定義驗證:
class Rental < ApplicationRecord
belongs_to :auto
validate :rental_period_is_available
private
def rental_period_is_available
return unless Rental
.where.not(id: id)
.where("rented_from < ? && ? < rented_until", rented_until, rented_from)
.exist?
errors.add(:base, "Car is already booked in this time period")
end
end
我建議閱讀官方 Rails Guides中的自定義驗證和一般驗證。
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/419428.html
標籤:
