2012-11-13 49 views
0

,我成功地提取從Facebook的散列數據:存儲在 「身份驗證」Rails的:使用OmniAuth(FB授權),讀取數據從Facebook哈希使用OmniAuth

# 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。用戶名行是空的。從測試中,我發現我無法存儲除提供程序和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」?

回答

2

關鍵是這樣的:我以錯誤的方式訪問auth哈希。答案是你做

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

以下是關於驗證散列的詳細信息:

:provider => 'facebook', 
:uid => '1234567', 

:info => { 
:nickname => 'jbloggs', 
:email => '[email protected]', 
: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 => '[email protected]', 
    :timezone => -8, 
    :locale => 'en_US', 
    :verified => true, 
    :updated_time => '2011-11-11T06:21:03+0000' 
} 

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

這就是爲什麼我可以簡單地訪問「供應商」和「UID」 auth [「provider」],我需要做

auth["info"]["name"] 

訪問名稱信息。

同樣,要獲得用戶的時區,你可以做

auth["extra"]["timezone"] 
+1

如果你想看看哈希退換,將它添加到你的行動上:'提高request.env ['omniauth.auth '] .to_yaml' – Ashitaka

+1

'render:text => request.env ['omniauth.auth']。inspect'也不錯! – johann