【问题标题】:ActiveModel validate attribute based on associationActiveModel 基于关联验证属性
【发布时间】:2012-08-23 08:28:08
【问题描述】:

我至少有 2 节课。一个类必须根据关联模型的属性值验证其属性之一。下面的代码是我想要的,但这只是一个想法,它不起作用。有什么方法可以实现吗?

class Concert
 include Mongoid::Document
 include Mongoid::Timestamps

 field :end_date, type: Date
end

class Sale
  include Mongoid::Document

  field :end_date, type: Date

  belongs_to :concert

  validates :end_date, :timeliness => {
        :before => lambda {self.concert.end_date}, 
        :after => lambda {self.concert.created_at}, 
        :before_message => 'Sale should not end before the Concert begins', 
        :after_message => 'Sale should not end after the Concert has already ended',
        :type => :date
    }
end

【问题讨论】:

  • 只是一个猜测,但您在 lambdas 中对 self 的引用没有问题吗?我会去=> lambda { |record| record.concert.end_date }
  • 你是对的。该代码只是为了说明我试图完成的事情,它不是实际的工作代码。我可以描述我正在尝试做的事情,我编写代码比用文字更容易。不过我会试试你说的。
  • 那你应该提供真实的例子,以便我们提供真正的帮助;)
  • 如果我不知道从哪里开始就不能给出真正的代码,这就是问题所在
  • @pduersteler 如果你用你的评论回答这个问题,我会将接受的答案改为你的:)

标签: ruby-on-rails validation associations mongoid activemodel


【解决方案1】:

只是一个猜测,但您在 lambdas 中对 self 的引用没有问题吗?我会去=> lambda { |record| record.concert.end_date }

【讨论】:

    【解决方案2】:

    向销售添加验证

    validates :end_date, :presence => true, :if => :some_checking
    
    def some_checking
       #your validations
       #eg
       self.concert.end_date.present?
    end
    

    【讨论】:

      猜你喜欢
      • 2017-07-13
      • 2019-02-05
      • 1970-01-01
      • 1970-01-01
      • 2016-10-31
      • 2019-09-14
      • 1970-01-01
      • 1970-01-01
      • 2011-10-04
      相关资源
      最近更新 更多