Matt Elhotiby
Matt Elhotiby

Reputation: 44066

Rails validation if a conditon is met

I have this validation

 validates :contact_id, :presence => true, :uniqueness => {:message => 'has an account already.'}

in the application.rb model

All is good but I need to only do this validation if the state is "invalid"

For example in the applications table there is a field called state and if there is a application with a contact_id of a user and the state is "invalid" then this validation should not take effect and should let the user save the application

Upvotes: 3

Views: 2809

Answers (2)

Geoff Lanotte
Geoff Lanotte

Reputation: 7510

I believe this should do it:

validates :contact_id,
    :presence => true,
    :uniqueness => {:message => 'has an account already.'},
    :if => :invalid?

def invalid?
    state == 'invalid'
end

you could also inline that to:

validates :contact_id,
    :presence => true,
    :uniqueness => {:message => 'has an account already.'},
    :if => lambda{ state == 'invalid' }

Hope this helps.

If you are going to do it when the state is not invalid, then you could do that two ways:

validates :contact_id,
    :presence => true,
    :uniqueness => {:message => 'has an account already.'},
    :unless => :invalid?

Or you could change it a bit more and have a valid message, which I might prefer:

validates :contact_id,
    :presence => true,
    :uniqueness => {:message => 'has an account already.'},
    :if => :valid?

def valid?
    state != 'invalid'
end

Upvotes: 9

Prashanth
Prashanth

Reputation: 1398

Did you try seeing this railscasts video ? http://railscasts.com/episodes/41-conditional-validations

validates :contact_id, :if => :should_validate_contactid?

def should_validate_contactid?
   Check condition
end

Upvotes: 4

Related Questions