Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/image/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby on rails 验证日期从具有多个属于关系_Ruby On Rails_Ruby_Validation_Model - Fatal编程技术网

Ruby on rails 验证日期从具有多个属于关系

Ruby on rails 验证日期从具有多个属于关系,ruby-on-rails,ruby,validation,model,Ruby On Rails,Ruby,Validation,Model,我在验证关系中的日期时遇到问题,我有很多/属于。 我正在制作一个Netflix网站来学习Rails,我想验证一集的过期日期是否在该集所属系列的过期日期之后 我尝试过这样做(我使用的是日期验证器gem): 一个系列(名称)有很多集,一个系列(名称,系列id)属于一个系列,这是我现在的代码表: class Episode < ApplicationRecord belongs_to :serie #validates :expire_date, date: { before:

我在验证关系中的日期时遇到问题,我有很多/属于。 我正在制作一个Netflix网站来学习Rails,我想验证一集的过期日期是否在该集所属系列的过期日期之后

我尝试过这样做(我使用的是日期验证器gem):

一个系列(名称)有很多集,一个系列(名称,系列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
课堂插曲
谢谢

写下你自己的:

课堂插曲{serie.nil?}##这可以防止潜在的nil错误
私有的
def验证\到期\日期
如果self.expire\u date>self.serie.expire\u date
添加(:expire\u date,'某种描述性错误消息')
结束
结束
结束
不需要宝石


验证只是一种方法,用于测试谓词并在验证失败时向errors对象添加错误。

谢谢,效果非常好,我刚刚添加了
!(self.serie.expire_date).nil?
到条件语句,检查该系列是否没有过期日期。
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