开发者

Can I check ActiveRecord validations without string matching?

开发者 https://www.devze.com 2023-02-05 15:36 出处:网络
Long story short, I want a user registration form to do something particular if an email address is already in the开发者_如何学C system, but use the normal error handling otherwise. The validations on

Long story short, I want a user registration form to do something particular if an email address is already in the开发者_如何学C system, but use the normal error handling otherwise. The validations on the model are already doing the work of figuring this out, so in the controller I'd like to be able to just check whether the email is non-unique. The problem is, it seems like the only way to make use of that work is to match against a specific string, e.g.

ruby-1.9.2-head :022 > user.valid?
=> false 
ruby-1.9.2-head :023 > user.errors
=> {:email=>["has already been taken"], :password=>["can't be blank"]} 
ruby-1.9.2-head :037 > user.errors[:email].include? "has already been taken"
=> true 

and that just seems terrible and fragile. Am I missing something? Is there a way to check if a model is invalid due to uniqueness without string matching? I could check the system for duplicate emails myself easily enough, but that seems like a waste when validation already provides that information.


There's no easy solution to your problem, as far as I know.

Aside from string matching and checking the database for existing records, the only thing I can think of is to eliminate all other possible errors.

For example, Devise validates the presence and uniqueness of the email address. If you can check whether user.email.present?, you can eliminate that issue. If those two validations (presence and uniqueness) are the only two validations on the email address, you'll know that validation failed because of uniqueness.

Now of course, Devise also checks the email to make sure it's a valid email address, which means you'll have to eliminate both the presence and format of the email, before you can safely conclude that the uniqueness is the failing factor.

All in all, your safest bet would probably be checking the database again. Your easiest option is to do the string matching. The only thing you'd have to guard for there is if the default error message changes in later Rails versions.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号