ActiveModel根据关联验证属性

时间:2012-08-28 19:10:16

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

我至少有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

2 个答案:

答案 0 :(得分:1)

向Sale添加验证

validates :end_date, :presence => true, :if => :some_checking

def some_checking
   #your validations
   #eg
   self.concert.end_date.present?
end

答案 1 :(得分:1)

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