0

当用户在 twitter 上注册时,我试图将他的姓名、位置等添加到他的用户记录中。我想我想做类似的事情user.build

这里是控制器。这就是发生的事情:

    user = User.new
    user.apply_omniauth(omni)
    if user.save
      flash[:notice] = "Logged In!"
      sign_in_and_redirect(:user, user)
    else
      session[:omniauth] = omni.except('extra')
      redirect_to new_user_registration_path
    end

当用户不存在 twitter 时,用户将被重定向到他们完成注册的注册路径。我想将来自 twitter 的额外内容添加到他们尚未保存的用户帐户中。我不能在该user.apply_omniauth(omni)方法中执行此操作,因为它会保存到身份验证表中。

有任何想法吗?

谢谢!

4

1 回答 1

1

您可以在方法中创建一个标志apply_omniauth来决定是否保存。

应用程序/模型/user.rb

# def apply_omniauth(omniauth) => def apply_omniauth(omniauth, save_it)
# apply_omniauth with save it flag
def apply_omniauth(omniauth, save_it = false)
  case omniauth['provider']
  when 'facebook'
    self.apply_facebook(omniauth)
  end
  self.email = omniauth['user_info']['email']
  if email.blank ? build_authentications(omniauth, save_it)
end

#build authentications
def build_authentications(omniauth, save_it = false)
  auth_params = {: provider = > omniauth['provider'],
      : uid = > omniauth['uid'],
      : token = > (omniauth['credentials']['token'] rescue nil)
  }
  if save_it authentications.create!(auth_params)
  else authentications.build(auth_params)
  end
end

#force to save
def apply_omniauth!(omniauth)
  apply_omniauth(omniauth, true)
end
于 2013-08-12T03:35:24.810 回答