2013-05-07 55 views
1

我正在使用postgres和devise在Rails 4上進行開發。我有以下用戶型號:Rails PG ::錯誤呈現和唯一約束處理

# 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 

電子郵件和用戶名是用戶表的唯一索引。我的用戶註冊視圖是從devise創建的。我創建了一個測試帳戶,例如,用戶名「test」,電子郵件「[email protected]」,密碼「123456」。我退出並嘗試註冊相同的信息。我期待的是:唯一性驗證觸發和旁邊的申請表單,錯誤的列表上呈現,而是我得到一個整版的誤差:

ERROR: duplicate key value violates unique constraint "index_users_on_email" DETAIL: Key (email)=([email protected]) already exists.

我怎樣才能讓這個錯誤冒泡到Rails,並顯示爲友好的單行錯誤,如「電子郵件已登記帳戶」旁邊的註冊表單,而不是被抓到一個大的Rails錯誤頁面?

回答

0

我發現了這個問題。插件friendly_id變得不那麼友好。它破壞了唯一性驗證,並導致500個內部服務器錯誤。我已將其從我的應用程序中刪除。考慮在Stringex庫中使用類似ActsAsUrl的內容。我已刪除

extend FriendlyId 
    friendly_id :username_copy, :use => :slugged 

,我現在使用

acts_as_url :username, :sync_url => true, :url_attribute => :slug 

生成友好的URL。

+0

我有同樣的問題,並沒有'UserId'與'User'模型 – Dorian 2015-01-20 10:59:33