gpt4 book ai didi

ruby-on-rails - Rails omniauth 不刷新数据

转载 作者:太空宇宙 更新时间:2023-11-03 16:02:01 25 4
gpt4 key购买 nike

我正在使用 omniauth-twitter gem 对用户进行身份验证,并在我的 User.rb 文件中填写姓名、头像等

  def self.from_omniauth(auth)
where(auth.slice("provider", "uid")).first || create_from_omniauth(auth)
end

def self.create_from_omniauth(auth)
create! do |user|
user.provider = auth["provider"]
user.uid = auth["uid"]
user.name = auth["info"]["name"]
user.nickname = auth["info"]["nickname"]
user.location = auth["info"]["location"]
user.image = auth["info"]["image"].sub("_normal", "")
user.description = auth["info"]["description"]
end
end
end

效果很好,除了我碰巧在 Twitter 上更改了我的头像,并注意到即使在我注销并重新授权后数据也不会改变。如果位置、图像、描述等数据在用户每次登录时都得到刷新,那就太好了。

最佳答案

好吧,该逻辑的运作取决于您。这是一个可能的解决方案示例:

def self.from_omniauth(auth)
user = find_by(auth.slice(:provider, :uid)) || initialize_from_omniauth(auth) # Rails 4
user = where(auth.slice(:provider, :uid)).first || initialize_from_omniauth(auth) # Rails 3
user.update_dynamic_attributes(auth)
end

def self.initialize_from_omniauth(auth)
new do |user|
user.provider = auth[:provider]
user.uid = auth[:uid]
user.name = auth[:info][:name]
end
end

def update_dynamic_attributes(auth)
self.location = auth[:info][:location]
self.image = auth[:info][:image]
self.description = auth[:info][:description]
save!
self
end

此外,您不必这样做:

auth["info"]["image"].sub("_normal", "")

如果您使用 image_size optionomniauth-twitter gem 已经可以为您做到这一点:

OmniAuth::Builder do
provider :twitter, ENV["TWITTER_KEY"], ENV["TWITTER_SECRET"], {
:image_size => 'original'
}
end

关于ruby-on-rails - Rails omniauth 不刷新数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22584964/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com