如果符合条件,则进行Rails验证

Mat*_*iby 3 validation ruby-on-rails ruby-on-rails-3

我有这个验证

 validates :contact_id, :presence => true, :uniqueness => {:message => 'has an account already.'}
Run Code Online (Sandbox Code Playgroud)

在application.rb模型中

一切都很好,但如果状态"无效",我只需要进行此验证

例如,在应用程序表中有一个被调用的字段state,如果有contact_id一个用户的应用程序且状态为"无效",则此验证不应生效,应让用户保存应用程序

Geo*_*tte 9

我相信这应该做到:

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

def invalid?
    state == 'invalid'
end
Run Code Online (Sandbox Code Playgroud)

你还可以内联到:

validates :contact_id,
    :presence => true,
    :uniqueness => {:message => 'has an account already.'},
    :if => lambda{ state == 'invalid' }
Run Code Online (Sandbox Code Playgroud)

希望这可以帮助.

如果你打算在状态not无效时这样做,那么你可以用两种方式做到:

validates :contact_id,
    :presence => true,
    :uniqueness => {:message => 'has an account already.'},
    :unless => :invalid?
Run Code Online (Sandbox Code Playgroud)

或者您可以更改一下并拥有有效的消息,我可能更喜欢这样:

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

def valid?
    state != 'invalid'
end
Run Code Online (Sandbox Code Playgroud)