是否可以使用omniauth-facebook rails gem保存多个用户?

时间:2014-01-16 22:11:21

标签: ruby-on-rails facebook ruby-on-rails-4 omniauth

我在user.rb中使用Facebook-omniauth gem在单个用户中登录以下代码:

 def self.from_omniauth(auth)
where(auth.slice(:provider, :fb_id)).first_or_initialize.tap do |user|
  user.provider          = auth.provider
  user.fb_id             = auth.uid
  user.name              = auth.info.name
  user.first_name        = auth["info"]["first_name"] unless auth["info"].blank?
  user.last_name         = auth["info"]["last_name"] unless auth["info"].blank?
  user.picture_url       = auth.info.image
  user.email             = auth.info.email
  user.oauth_token       = auth.credentials.token unless auth["info"].blank?
  user.location          = auth.info.location unless auth["info"].blank?
  user.save!
end

我想为多个Facebook用户构建用户帐户。当我记录它的罚款,但当另一个人登录时,该应用程序将替换我的用户实例。有没有办法继续从这个宝石构建用户帐户?

谢谢!

1 个答案:

答案 0 :(得分:0)

解决方案位于第二行:where(auth.slice(:provider, :fb_id))

我将它从:uid更改为:fb_id以匹配我所有其他表中其他所有内容的facebook id但是在检查auth哈希之后我意识到:fb_id根本找不到,因此不是产生任何新用户。

我将用户fb_id列重命名为uid,现在可以正确收集新用户:

def self.from_omniauth(auth)
    where(auth.slice(:provider, :uid)).first_or_initialize.tap do |user|
      user.provider          = auth.provider
      user.uid               = auth.uid
      user.name              = auth.info.name
      user.first_name        = auth["info"]["first_name"] unless auth["info"].blank?
      user.last_name         = auth["info"]["last_name"] unless auth["info"].blank?
      user.picture_url       = auth.info.image.sub("square", "large")
      user.email             = auth.info.email
      user.oauth_token       = auth.credentials.token unless auth["info"].blank?
      user.location          = auth.info.location unless auth["info"].blank?
      user.save!
    end
  end