我正在使用 postgres 和设计在 Rails 4 上开发。我有以下用户模型:
# user model
class User < ActiveRecord::Base
extend FriendlyId
friendly_id :username, :use => :slugged
rolify
devise :database_authenticatable, :registerable, :recoverable, :rememberable, :trackable
validates :username, :presence => true, :uniqueness => {:case_sensitive => false}, :length => { :minimum => 3 },
:format => { :with => /\A[A-Z0-9a-z\w\b\ \-\_\'\!&@#\.]+\z/i,
:message => "may contain only alphanumeric characters and common special characters." }
validates :email, :uniqueness => {:case_sensitive => false}, :presence => true,
:format => { :with => Devise.email_regexp, :message => "isn't valid"}
validates :password, length: { in: 6..128 }, on: :create
validates :password, length: { in: 6..128 }, on: :update, allow_blank: true
validates :slug, :presence => true
end
# in schema
create_table "users", force: true do |t|
t.string "email", default: "", null: false
t.string "encrypted_password", default: "", null: false
t.string "reset_password_token"
t.datetime "reset_password_sent_at"
t.datetime "remember_created_at"
t.integer "sign_in_count", default: 0
t.datetime "current_sign_in_at"
t.datetime "last_sign_in_at"
t.string "current_sign_in_ip"
t.string "last_sign_in_ip"
t.datetime "created_at"
t.datetime "updated_at"
t.string "username"
t.string "slug"
end
add_index "users", ["email"], name: "index_users_on_email", unique: true
add_index "users", ["reset_password_token"], name: "index_users_on_reset_password_token", unique: true
add_index "users", ["slug"], name: "index_users_on_slug", unique: true
add_index "users", ["username"], name: "index_users_on_username", unique: true
字段 email 和 username 是 users 表的唯一索引。我的用户注册视图是从设计创建的。我创建了一个测试帐户,例如,用户名“test”,电子邮件“test@example.com”,密码“123456”。我退出并尝试使用相同的信息进行注册。我期望 :uniqueness 验证触发并呈现在注册表单旁边的错误列表中,但我得到了一个整页错误:
错误:重复的键值违反了唯一约束“index_users_on_email”详细信息:键(电子邮件)=(test@example.com)已经存在。
我怎样才能让这个错误冒泡到 Rails 并在注册表单旁边显示为友好的单行错误,例如“电子邮件已使用帐户注册”,而不是被一个大的 Rails 错误页面捕获?