Conditional Validation

I am doing conditional validation for a numeric field like this in my model

class AdditionalExam < ActiveRecord::Base validates_presence_of :minimum_marks,:if=>:validate_grades?

belongs_to :additional_exam_group

def validate_grades?    puts"#{self.additional_exam_group.exam_type}" end

  def before_save     puts"#{self.additional_exam_group.exam_type}"   end end

1. Note the belongs_to code.

2. The puts statement in the validate_grade method gives error, that exam_type is undefined for nil class (i think additional_exam_group)

3. Same code works fine in the before_save method.

Why is this happening?

I am doing conditional validation for a numeric field like this in my model

class AdditionalExam < ActiveRecord::Base validates_presence_of :minimum_marks,:if=>:validate_grades?

belongs_to :additional_exam_group

def validate_grades? puts"#{self.additional_exam_group.exam_type}" end

def before_save puts"#{self.additional_exam_group.exam_type}" end end

1. Note the belongs_to code.

noted

Firstly, (since the validate_grades? method does no actual checking for validation...) I'm assuming you're using those "puts" as debugging aids. If so, it would be better to actually use the Ruby debugging functionality, and leave your validation code in place.

2. The puts statement in the validate_grade method gives error, that exam_type is undefined for nil class (i think additional_exam_group)

That's letting you know that there isn't an associated additional_exam_group. You could change the validate_grades? [1] to check for an additional_exam_group before progressing.

  def validate_grades?     return false unless self.additional_exam_group     return true if .... # some validation code here...   end

If the additional_exam_group is mandatory regardless, add a:   validates_presence_of :additional_exam_group

3. Same code works fine in the before_save method. Why is this happening?

Is there any other code in the model that you've stripped-out for this example? Maybe something is messing with the additional_exam_group between the validate and before_save callbacks?

[1] Given the question mark, I'd call it "valid_grades?" to read nicely, but that's just personal preference :wink: