Validate uniqueness of two columns

2019-05-29 21:04发布

问题:

I am trying to validate that two columns are unique in my User model. I've searched Google and from what I understand the following code will not work:

validates :login, :uniqueness=>true
validates :email, :uniqueness=>true

In my case doing that will validate the uniqueness of email, but will not validate the uniqueness of login. I set that login must be unique on the database. However, all that will do is generate a runtime error if it already exists. I don't want that error in production because it would result in a 500 internal server error, which the user would not understand.

Any ideas on how I could validate the uniqueness of both of these fields?

Authentication Used:

  • CanCan
  • Devise
  • Devise Invitable

Update:

From what I can tell the problem is being caused by Devise, specifically the validatable module, which validate email and password.

Update 2:

Removing the validatable module from Devise will result in neither checking for uniqueness.

Update 3:

It appears that devise is not causing the problem. Rather, a gem called Devise Invitable is. Removing this gem results in the validation being triggered. It also appears that this gem tries to force validations of the email field. It makes sense due to the nature of this gem, but shouldn't be blocking.

回答1:

Should be able to do it with scope, adding to the default validation by devise.

For Rails 3 versions :

validates :email, :uniqueness => {:scope => :login}

Ref:

  • rails 3 validation on uniqueness on multiple attributes
  • How do I validate two fields for uniqueness
  • API doc for validates_uniqueness_of


回答2:

The problem was with the devise_invitable gem. In the devise initializer I had to set

  config.validate_on_invite = true

to make sure the validations were executed, the default is false. I also had to remove the devise validatable module.



回答3:

The code works perfectly fine on the Rails 3.2.8..I have tested on it...

maybe there are some problems with your gems...