2017-07-27 87 views
0

我有兩個型號:Ruby on Rails的 - 驗證與關聯的模型屬性之

class ModelA < ApplicationRecord 
    has_many: :model_b 
end 

class ModelB < ApplicationRecord 
    belongs_to: :model_a 
end 

兩種型號都有star_dateend_date,我想驗證德ModelB日期是ModelA日期之間。這樣的事情:

class ModelB < ApplicationRecord 
    belongs_to: :model_a 
    validates :start_date, after_date: ModelA.start_date 
end 

我是新來的Rails,我不知道該怎麼做。

謝謝!

+0

https://hackernoon.com/performing-cust om-validations-in-rails-an-example-9a373e807144 –

回答

1

您將需要添加自定義驗證

class ModelA < ActiveRecord::Base 
    has_many: :model_b 
end 

class ModelB < ActiveRecord::Base 
    belongs_to : model_a 
    validates :is_between_parent_period 

    private 

    def is_between_parent_period 
    unless start_date.between?(self.model_a.start_date, self.model_a.end_date) && end_date.between?(self.model_a.start_date, self.model_a.end_date) 
     errors.add(:base, 'Must be between parent start date and end date') 
    end 
    end 
end 
+0

謝謝,它工作! – TADebastiani

0

的檢查,如果兩個日期或時間範圍A和B重疊,需要覆蓋很多的情況下:

A partially overlaps B 
A surrounds B 
B surrounds A 
A occurs entirely after B 
B occurs entirely after A 

做了簡單的檢查重疊您可以在模型A中創建方法,然後通過另一個模型(模型b)作爲參數

class ModelA < ActiveRecord::Base 
    has_many: :model_b 

    # Check if a given interval overlaps this interval  
    def overlaps?(other) 
    (self.start_date - other.end_date) * (other.start_date - self.end_date) >= 0 
    end 
end 
+0

您的回答很有用,我將在驗證中使用此代碼。謝謝。 – TADebastiani