2015-09-29 68 views
6

如何更改以下代碼,以便用Facebook登錄的用戶可以跳過確認並確認設計?我嘗試在user.email...的行下添加user.skip_confirmation!,但這不起作用。使用omniauth時設計跳過確認

user.rb:

# Finds or creates user based on omniauth hash from given provider 
    def self.from_omniauth(auth) 
    where(provider: auth.provider, uid: auth.uid).first_or_create do |user| 
     user.provider = auth.provider 
     user.uid = auth.uid 
     user.first_name = auth.info.first_name 
     user.last_name = auth.info.last_name 
     user.email = auth.info.email 
    end 
    end 

    # Overrides class method 'new_with_session' to persist and validate attributes 
    def self.new_with_session(params, session) 
    if session["devise.user_attributes"] 
     new(session["devise.user_attributes"], without_protection: true) do |user| 
     user.attributes = params 
     user.valid? 
     end 
    else 
     super 
    end 
    end 

omniauth_callbacks_controller.rb

class Users::OmniauthCallbacksController < Devise::OmniauthCallbacksController 

    def all 
    user = User.from_omniauth(request.env["omniauth.auth"]) 
    if user.persisted? 
     flash.notice = "Signed in!" 
     sign_in_and_redirect user 
    else 
     session["devise.user_attributes"] = user.attributes 
     redirect_to new_user_registration_url 
    end 
    end 
    alias_method :facebook, :all 
end 

回答

8

嘗試對first_or_initialize

def self.from_omniauth(auth) 
    where(provider: auth.provider, uid: auth.uid). first_or_initialize do |user| 
     user.provider = auth.provider 
     user.uid = auth.uid 
     user.first_name = auth.info.first_name 
     user.last_name = auth.info.last_name 
     user.email = auth.info.email 
     user.skip_confirmation! 
     user.save! 
    end 
    end 
+0

其實我增加了行'user.confirmed_at = Time.zone。現在',它似乎工作。你能看到有這樣的問題嗎?謝謝 – user4584963

+1

你可以使用'user.confirm' @ user4584963 http://www.rubydoc.info/github/plataformatec/devise/Devise/Models/Confirmable#confirm-instance_method – illusionist

+0

@ user4584963它實際上是一樣的東西,但' skip_confirmation!'是有原因的。據我所知,更好的編碼實踐。請參閱[docs for it](http://www.rubydoc.info/github/plataformatec/devise/Devise%2FModels%2FConfirmable%3Askip_confirmation%21) –