2

I have at least 2 classes. One class must validate one of its attributes based on the value of an associated model's attributes. The below code is what I am going for, but its just an idea, it doesn't work. Any way to achieve it?

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
chris
  • 6,653
  • 6
  • 41
  • 54
  • 1
    just a guess, but isn't there a problem with your reference to `self` in your lambdas? I'd go for `=> lambda { |record| record.concert.end_date }` – pdu Aug 28 '12 at 19:16
  • you are correct. the code is just to illustrate what im trying to accomplish, it is not actual working code. I can just describe what I'm trying to do i code more easily than i can with words. I will try what you said though. – chris Aug 28 '12 at 19:18
  • Then you should provide real examples so we can give real help ;) – pdu Aug 28 '12 at 19:19
  • Cant give real code if i dont know where to begin, which is what the question is about – chris Aug 28 '12 at 19:21
  • You should look at custom validation method, this way you could implement the checks that suits you : http://guides.rubyonrails.org/active_record_validations_callbacks.html#custom-methods – Baldrick Aug 28 '12 at 20:03
  • 1
    @pduersteler if you answer this with your comment, I'll change accepted answer to yours :) – chris Sep 10 '12 at 20:13

2 Answers2

1

add validation to Sale

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

def some_checking
   #your validations
   #eg
   self.concert.end_date.present?
end
Prasad Surase
  • 6,486
  • 6
  • 39
  • 58
1

just a guess, but isn't there a problem with your reference to self in your lambdas? I'd go for => lambda { |record| record.concert.end_date }

pdu
  • 10,295
  • 4
  • 58
  • 95