如何避免错误 ->双重输入 [英] How to avoid error -> Duplicate entry

查看:48
本文介绍了如何避免错误 ->双重输入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

表用户(带id、用户名、密码、is_admin)

table user (with id, username, password, is_admin)

我的控制器(我添加的地方)

my controller (where i adding)

  def create
    @user = User.new(params[:respondent])
#   entered     = User.find(:all, :conditions => ["email = ?", @user])
    render :json => @user.to_ext_json(:success => @user.save)
    return false 
  end

当我粘贴同一封电子邮件时,我得到了这个:

When i pasting the same email, i got this:

pre>Mysql::Error: Duplicate entry 'sam@sa.com' for key 'email': INSERT INTO `users` (`created_at`, `updated_at`, `email`) VALUES('2011-05-05 09:05:57', '2011-05-05 09:05:57', 'sam@sa.com')</pre>

如何避免这种情况?我应该在控制器中写什么(一些如果?)

How to avoid this? What i should write in controller (some if?)

谢谢!

推荐答案

您可以验证模型中的唯一性

you can either validate uniqueness in your model

validates :email, :uniqueness => :true

或者你可以像这样在你的控制器中拯救 RecordNotUnique

or you can rescue RecordNotUnique in your controller like so

begin
  # create user
rescue ActiveRecord::RecordNotUnique => e
  # handle duplicate entry
end

这篇关于如何避免错误 ->双重输入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆