2011-06-16 87 views
2

我知道有噸教程已經解釋如何做到這一點的,但我已經花了太多時間試圖使其無功而返工作...Rails 3 + Devise 1.3.4:如何使用用戶名登錄?

官方文檔:https://github.com/plataformatec/devise/wiki/How-To:-Allow-users-to-sign_in-using-their-username-or-email-address

在他們解釋瞭如何使用用戶名或電子郵件登錄的官方文檔。我只想使用用戶名登錄。

我所做的:

1. rails generate migration add_username_to_users username:string 
2. rake db:migrate 
3. rails generate devise:views 

我的應用程序/模型/ user.rb:(我只加:在attr_accessible用戶名)

class User < ActiveRecord::Base 
    # Include default devise modules. Others available are: 
    # :token_authenticatable, :encryptable, :confirmable, :lockable, :timeoutable and :omniauthable 
    devise :database_authenticatable, :registerable, :recoverable, :rememberable, :trackable, :validatable 

    # Setup accessible (or protected) attributes for your model 
    attr_accessible :username, :email, :password, :password_confirmation, :remember_me 

end 

我的配置/初始化/ devise.rb :

... 
config.authentication_keys = [ :username ] 
... 

我的應用程序/視圖/設計/會話/ new.html.erb:

... 
    <p><%= f.label :username %><br /> 
    <%= f.text_field :username %></p> 
... 

我相信這是一切都有改變,但它只會說「無效的電子郵件或密碼」。

謝謝你的幫助..!

+0

雖然它並沒有解決你的問題。 「無效的電子郵件或密碼」消息位於config/local/en.yml用戶設備:失敗:無效 如果您將其更改爲驗證用戶名,則應更改該設置。 – Olives 2011-06-17 18:15:15

回答

1

你必須改變線config/locales/devise.en.yml。更改:

invalid:email or password 

要:

invalid:username or password 
1

您是否像在Devise文檔中提到的那樣提供了find_for_database_authentication方法?

事情是這樣的:

protected 

def self.find_for_database_authentication(warden_conditions) 
    conditions = warden_conditions.dup 
    login = conditions.delete(:login) 
    where(conditions).where(["lower(username) = :value", { :value => login.downcase }]).first 
end 

應該使其工作。

+0

這是萬一你想要有2種登錄,我只想保留1,但不同的。我認爲我不應該改變這一點 - 這至少是我在文章中看到的。 這個def必須寫入什麼文件?我還是個初學者.. :) .. – Etienne 2011-06-16 20:18:20

+0

不,我已經改變了方法的where條件,只保留用戶名。您必須將其添加到用戶模型(app/models.user.rb),如Jhonny所述。 – 2011-06-20 12:00:51

0

一下添加到app/models/user.rb

def self.find_for_database_authentication(conditions={}) 
    self.where("username = ?", conditions[:username]).limit(1).first 
end 
相關問題