2011-06-10 54 views
0

我有一个用户模型,看起来像:Rails - 如何有条件启用验证?

class User < TwitterAuth::GenericUser 

acts_as_authentic {|c| 
    c.login_field = :email 
    c.validate_email_field = false 
    c.validate_password_field = false 
    } 
end 

它采用TwitterAuth和Authlogic插件。

我想根据用户是否使用twitter通过普通电子邮件注册来选择性地禁用验证c.validate_email_field = false 。

- With email and password registration, the validations needs to be on. 
-twitter does not have email or password fields, the validation needs to be off. 

When I disable validation, the authLogic user registration using email and password fails: 

unknown attribute: password_confirmation 


I tried to selectively disable validation if attribute 'twitter_id' is present. 

c.merge_validates_confirmation_of_password_field_options({:unless => :skip_password_validation?}) 

def skip_password_validation 
    !attribute_present?('twitter_id') 
end 

这不起作用,因为表格中存在的属性'twitter_id'无论是否使用。

如何有选择地启用电子邮件和密码验证? i,e仅在未使用twitter oAuth时启用验证。

感谢您的帮助

回答

1

我想你也许需要看看其他验证方法,如validates_with那的意思为更复杂的验证逻辑。然后,您应该能够验证你根据什么被通过在需要的属性

+0

看起来像validates_with只是Rails 3.0。不幸的是我在2.3.5上,这似乎不是一种选择。 – truthSeekr 2011-06-10 19:07:47

+1

是的,你是对的。在2.3.x中,我想你必须直接覆盖'validate'方法。看看'ActiveRecord :: Validations'的例子。祝你好运! – harald 2011-06-11 15:09:56