使用omniauth的rails项目-卡在评估nil.[]错误上

发布于 2024-12-28 18:15:01 字数 926 浏览 2 评论 0原文

我在我的 Rails 项目上使用omniauth 来通过facebook 进行身份验证。

我还尝试从omniauth 获取用户当前的城市,当用户在facebook 中拥有当前的城市时,这效果很好。

额外的: 用户哈希: 姓名:杰夫·特纳 地点: 名称:加利福尼亚州奥克兰,

但是当用户没有任何内容时,我无法设置该值

current_city = user_data['location']['name']

错误: 当你没有预料到的时候,你得到了一个 nil 对象! 您可能期望一个 ActiveRecord::Base 的实例。 评估 nil 时发生错误。[]

这些属性甚至没有从omniauth 返回任何值,

我可以看到,如果我尝试测试 nil 条件,

if user_data['location']['name'].blank? == false
current_city = user_data['location']['name']
end

我似乎在第一行 (user_data[ 'location']['name'].blank?)

仍然无法评估nil。

我对 Rails 还很陌生,所以我希望我错过了一些明显的东西。

更新

这就是我最终将其更改为的内容,并且效果很好。下面的答案看起来也可以

if user_data['location'].nil? == false
  if user_data['location']['name'].nil? == false
   current_city = user_data['location']['name']
  end
end

I am using omniauth on my rails project to authenticate with facebook.

I am also trying to get the user's current city from omniauth, and that works great when the user has their current city in facebook.

extra:
user_hash:
name: Jeff Turner
location:
name: Oakland, California

but when the user doesn't have anything, I cant set that value

current_city = user_data['location']['name']

error:
You have a nil object when you didn't expect it!
You might have expected an instance of ActiveRecord::Base.
The error occurred while evaluating nil.[]

I can see that no value with those attributes even come back from omniauth

if I try to test for the nil condition

if user_data['location']['name'].blank? == false
current_city = user_data['location']['name']
end

I seem to get the same error on that first line (user_data['location']['name'].blank?)

still cant evaluate nil.

I am pretty new to rails, so I hope I just missed something obvious.

Update

this is what I ended up changing it to and it worked fine. answer below looks like it would work as well

if user_data['location'].nil? == false
  if user_data['location']['name'].nil? == false
   current_city = user_data['location']['name']
  end
end

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

缱绻入梦 2025-01-04 18:15:01

您可以尝试执行以下操作:

current_city = auth.fetch('location', []).fetch('name', nil)

使用 fetch< /a>.

You can try doing something like this:

current_city = auth.fetch('location', []).fetch('name', nil)

Using fetch.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文