On 16 March 2011 06:43, mnj
<mkkmugdha2-Re5JQEeQqe8AvxtiuMwx3w@public.gmane.org>
wrote:> 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 ;-)
--
You received this message because you are subscribed to the Google Groups
"Ruby on Rails: Talk" group.
To post to this group, send email to
rubyonrails-talk-/JYPxA39Uh5TLH3MbocFF+G/Ez6ZCGd0@public.gmane.org
To unsubscribe from this group, send email to
rubyonrails-talk+unsubscribe@googlegroups.com.
For more options, visit this group at
http://groups.google.com/group/rubyonrails-talk?hl=en.