5

I'm trying to validate a model attribute based on a simple condition as shown in the rails docs. I have a quiz model with a boolean "show_birthday" attribute, and a participant model with a birthday attribute. Here's the relevant part of my code:

class Participant < ActiveRecord::Base
    belongs_to :quiz
    validates :birthday, presence: true, :if => :has_birthday?

    def has_birthday?
        quiz.show_birthday?
    end
end

The validation works if I remove the if condition, but does not work even if I change the part inside the has_birthday? method to "true". Any ideas on why this isn't working?

dvanderb
  • 757
  • 2
  • 8
  • 20
  • Have you tried using an inline proc? – pdoherty926 Jun 12 '13 at 17:08
  • I did try that as well. The code I tried there was: :if => Proc.new { |p| p.quiz.show_birthday? } (also tried the same thing with an inline lambda) – dvanderb Jun 12 '13 at 17:09
  • is it possible that `Participant` doesn't have a `quiz` record? Although in that case it should raise a nil error... – Cody Caughlan Jun 12 '13 at 17:11
  • In the form view for a new participant I did this <%= "Should validate birthday" if @participant.has_birthday? %> and it shows up when the quiz has show_birthday? marked true... – dvanderb Jun 12 '13 at 17:12
  • define the `has_birthday?` as `self.has_birthday?` and see if it works? – uday Jun 12 '13 at 17:35
  • 2
    For code consistency reasons try using only one format of param => value `validates :birthday, :presence => true, :if => :has_birthday?`. This probably isn't the problem with your code, though... it should be working, are you testing in the console and have you restarted said console after changing the validation? – Matt Jun 12 '13 at 17:38
  • What happens if you use `:if => "quiz.show_birthday?"` as your `if` clause? (alternative method to check) – lurker Jun 12 '13 at 17:46
  • Nothing seems to be working. If I ad an if clause to any of my validations, they seem to stop working... – dvanderb Jun 12 '13 at 17:50
  • Have you seen [this](http://stackoverflow.com/a/5049311/382982) answer? – pdoherty926 Jun 12 '13 at 17:50
  • I still have no idea why the conditional validation won't fire, but I got around the issue by writing my own. I'm doing validate :birthday_if_necessary and defining that method which includes a check for whether or not the quiz has show_birthday set to true. – dvanderb Jun 12 '13 at 18:01

0 Answers0