如何使用 omniauth 从 facebook 获取时区?

How to get timezone from facebook with omniauth?

user.rb 中的所有内容都在注册时正确传递,但时区除外。我不明白为什么我在用户尝试登录时收到此 错误

2016-03-30T20:13:38.083469+00:00 app[web.1]:   NoMethodError (undefined method `timezone=' for #<User:0x007fdd2976e338>):
2016-03-30T20:13:38.083470+00:00 app[web.1]:   app/models/user.rb:72:in `block in from_omniauth'
2016-03-30T20:13:38.083471+00:00 app[web.1]:   app/models/user.rb:66:in `tap'
2016-03-30T20:13:38.083471+00:00 app[web.1]:   app/models/user.rb:66:in `from_omniauth'
2016-03-30T20:13:38.083472+00:00 app[web.1]:   app/controllers/sessions_controller.rb:7:in `facebook'

user.rb

  def self.from_omniauth(auth)
     # Sets 60 day auth token
     oauth = Koala::Facebook::OAuth.new("1540371223342976229929", "ee917abf2e8f1c98274cd323fa1234ebb1346f4") # Fake Numbers
     new_access_info = oauth.exchange_access_token_info auth.credentials.token

     new_access_token = new_access_info["access_token"]
     new_access_expires_at = DateTime.now + new_access_info["expires"].to_i.seconds

    where(provider: auth.provider, uid: auth.uid).first_or_initialize.tap do |user|
      user.provider = auth.provider
      user.image = auth.info.image
      user.uid = auth.uid
      user.name = auth.info.first_name
      user.last_name = auth.info.last_name
      user.timezone = auth.info.timezone
      user.email = auth.info.email unless user.email.present?
      user.oauth_token = new_access_token # auth.credentials.token <- your old token. Not needed anymore.
      user.oauth_expires_at = Time.at(auth.credentials.expires_at)
      user.password = (0...8).map { (65 + rand(26)).chr }.join
      user.activated = true
      user.save!
    end
  end

config/omniauth.rb

Rails.application.config.middleware.use OmniAuth::Builder do
  provider :facebook, "1540324372976229929", "ee917abf2e8423f1c98274cdfa234234ebb1346f4", {info_fields: 'email, first_name, last_name, timezone'}
end

t.float "timezone" Facebook docs 说时区应该是 float.

omniauth 提供的 auth hash 看起来与您使用的结构有点不同。试试这个。

user.timezone = auth.extra.raw_info.timezone

Here is the hash structure 可用于 Facebook omniauth。