2

私は少なくとも2つのクラスを持っています。1 つのクラスは、関連付けられたモデルの属性の値に基づいて、その属性の 1 つを検証する必要があります。以下のコードは私が目指しているものですが、それは単なるアイデアであり、機能しません。それを達成する方法はありますか?

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
4

2 に答える 2

1

推測ですが、ラムダでの参照に問題はありませんselfか? 私は行くだろう=> lambda { |record| record.concert.end_date }

于 2012-09-10T20:54:40.237 に答える
1

販売に検証を追加する

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

def some_checking
   #your validations
   #eg
   self.concert.end_date.present?
end
于 2012-08-29T06:51:17.747 に答える