Rails - 在用户创建之前添加属性

时间:2013-08-12 02:12:40

标签: ruby-on-rails omniauth

当用户向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)方法中执行此操作,因为它会保存到身份验证表中。

有什么想法吗?

谢谢!

1 个答案:

答案 0 :(得分: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