从has_many-belongs_to关系验证日期

我有一个在关系has_many / belong_to中验证日期的问题。 我正在制作一个Netflix网站以学习Rails,并且我想验证某个情节的到期日期是否不晚于属于该情节的系列的到期日期。

我试图做这样的事情(我正在使用日期验证器gem):

一个Serie(名称)具有许多情节,而一个情节(名称,serie_id)属于一个系列,这是我现在的代码形式:

class Episode < ApplicationRecord
    belongs_to :serie
    #validates :expire_date,date: { before: Serie.find(:serie_id).expire_date } #This line explodes,that's what I want to fix
end

class Serie < ApplicationRecord
    has_many :episodes,dependent: :destroy
}
end

谢谢!

ASD52113144 回答:从has_many-belongs_to关系验证日期

只需编写自己的validation method

class Episode < ApplicationRecord
  belongs_to :serie

  validate :validate_expiry_date,unless: ->{ serie.nil? } #  # this prevents a potential nil error

  private

  def validate_expiry_date
    if self.expire_date > self.serie.expiry_date
      errors.add(:expire_date,'some sort of descriptive error message')
    end
  end
end

不需要宝石。

验证只是一种测试谓词并将验证失败的错误添加到错误对象的方法。

本文链接:https://www.f2er.com/3169649.html

大家都在问