Devise + omniauth(facebook)+ Profile Model

时间:2016-04-19 11:02:40

标签: ruby-on-rails-4 devise omniauth user-profile omniauth-facebook

我想通过设计注册或Omniauth-facebook创建用户时自动创建配置文件。我有用户模型(user.rb)

 class User < ActiveRecord::Base
 devise :database_authenticatable, :registerable,
     :recoverable, :rememberable, :trackable, :validatable,
     :omniauthable, :omniauth_providers => [:facebook]

has_many :listings, dependent: :destroy
has_many :bookings, dependent: :destroy
has_one :profile, dependent: :destroy

before_create :build_profile

  def self.from_omniauth(auth)

where(provider: auth.provider, uid: auth.uid).first_or_create do |user|
user.email = auth.info.email
user.password = Devise.friendly_token[0,20]
#Profile.where(:user_id => user.id).update_all(name: auth.info.name)
user.build_profile(name: auth.info.name)
   end
  end
 end

但如果我在Facebook上使用before_create:build_profile和sign_in,则会创建两个配置文件 如果我在self.from_omniauth(auth)中使用user.build_profile(name:auth.info.name),那么如果我使用Devise ..no profile创建配置文件。 那么在这段代码中我构建配置文件? 我的omniauth_callbacks_controller.rb

class Users::OmniauthCallbacksController <    Devise::OmniauthCallbacksController

def facebook
# You need to implement the method below in your model (e.g. app/models/user.rb)


@user = User.from_omniauth(request.env["omniauth.auth"])

if @user.persisted?
  sign_in_and_redirect @user, :event => :authentication #this will throw if @user is not activated
  set_flash_message(:notice, :success, :kind => "Faceboo") if is_navigational_format?

else
  session["devise.facebook_data"] = request.env["omniauth.auth"]
  redirect_to new_user_registration_url
 end
end

def failure
redirect_to root_path
 end

end

0 个答案:

没有答案