Rails:使用OmniAuth(FB授权),从Facebook Hash读取数据

使用OmniAuth,我成功从Facebook获取哈希数据:存储在“auth”中

# extra=#] last_name="Jordan" link="http://www.facebook.com/michael" locale="en_US" middle_name="Ball" name="Michael Jordan" quotes="\"lalala\"\n\n\"lala\"" timezone=9 updated_time="2011-09-01T20:25:58+0000" username="mjordan82" verified=true>> info=# verified=true> provider="facebook" uid="123456879"> 

在用户模型中,我执行如下操作:

 def self.create_with_omniauth(auth) create! do |user| user.provider = auth["provider"] user.uid = auth["uid"] user.name = auth["name"] end end 

当我检查数据库时,我只有提供者和uid。 User.name行为空。 从测试中,我发现我无法存储除提供者和uid之外的其他数据。 例如,user.name = auth [“provider”]或user.name = auth [“uid”]存储没有问题,但是当我尝试类似user.name = auth [“timezone”]或user.name =时auth [“last_name”],没有任何内容存储在变量中。 有人知道怎么修这个东西吗? 我也试过user.name = auth [“user_info”] [“name”],但是它返回了一个错误。

我不确定为什么user.name = auth [“name”]不存储任何内容。 换句话说,为什么auth [“name”]在这种情况下不是“Michael Jordan”?

关键是: 我以错误的方式访问auth哈希。 答案就是你做的

 user.name = auth["info"]["name"] 

以下是有关Auth Hash的详细信息:

 :provider => 'facebook', :uid => '1234567', :info => { :nickname => 'jbloggs', :email => 'joe@bloggs.com', :name => 'Joe Bloggs', :first_name => 'Joe', :last_name => 'Bloggs', :image => 'http://graph.facebook.com/1234567/picture?type=square', :urls => { :Facebook => 'http://www.facebook.com/jbloggs' }, :location => 'Palo Alto, California', :verified => true }, :credentials => { :token => 'ABCDEF...', # OAuth 2.0 access_token, which you may wish to store :expires_at => 1321747205, # when the access token expires (it always will) :expires => true # this will always be true }, :extra => { :raw_info => { :id => '1234567', :name => 'Joe Bloggs', :first_name => 'Joe', :last_name => 'Bloggs', :link => 'http://www.facebook.com/jbloggs', :username => 'jbloggs', :location => { :id => '123456789', :name => 'Palo Alto, California' }, :gender => 'male', :email => 'joe@bloggs.com', :timezone => -8, :locale => 'en_US', :verified => true, :updated_time => '2011-11-11T06:21:03+0000' } 

来源: https : //github.com/mkdynamic/omniauth-facebook

这就是我可以通过简单的auth [“provider”]访问“provider”和“uid”的原因,我需要这样做

 auth["info"]["name"] 

访问名称信息。

同样,要获得用户的时区,您可以这样做

 auth["extra"]["timezone"]