我有一个使用Omni-Auth GitHub gem的Rails应用程序。用户帐户创建和通过GitHub登录可以完美运行!
这是我的用户模型:
def self.from_omniauth(auth)
find_by_github_uid(auth["uid"]) || create_from_omniauth(auth)
end
def self.create_from_omniauth(auth)
create! do |user|
user.github_uid = auth["uid"]
user.github_token = auth["credentials"]["token"]
user.username = auth["info"]["nickname"]
user.email = auth["info"]["email"]
user.full_name = auth["info"]["name"]
user.gravatar_id = auth["extra"]["raw_info"]["gravatar_id"]
user.blog_url = auth["extra"]["raw_info"]["blog"]
user.company = auth["extra"]["raw_info"]["company"]
user.location = auth["extra"]["raw_info"]["location"]
user.hireable = auth["extra"]["raw_info"]["hireable"]
user.bio = auth["extra"]["raw_info"]["bio"]
end
end
但有时用户改变他们的生物或公司,或者他们想要被雇用,所以我不想删除旧账户,我认为如果在他们更新他们后及时更新他们将会很好帐户。
执行此操作的最佳做法是什么?如何使用现有的OmniAuth代码更新用户信息?
答案 0 :(得分:5)
def self.from_omniauth(auth)
user = find_by_github_uid(auth["uid"]) || User.new
user.assign_from_omniauth(auth).save!
end
def assign_from_omniauth(auth)
self.github_uid ||= auth["uid"]
self.github_token ||= auth["credentials"]["token"]
self.username ||= auth["info"]["nickname"]
self.email ||= auth["info"]["email"]
self.full_name = auth["info"]["name"]
self.gravatar_id = auth["extra"]["raw_info"]["gravatar_id"]
self.blog_url = auth["extra"]["raw_info"]["blog"]
self.company = auth["extra"]["raw_info"]["company"]
self.location = auth["extra"]["raw_info"]["location"]
self.hireable = auth["extra"]["raw_info"]["hireable"]
self.bio = auth["extra"]["raw_info"]["bio"]
end