使用Rails 5,我尝试实现Omniauth-Facebook和Clearance进行用户身份验证。
注意:我的代码就是这样的Gist
我得到它大部分工作。但是,在使用Facebook进行注册时(即,用户从未访问过该网站),Rails会抛出错误信息Validation failed: User must exist
。我将要点缩小到要点中的这一部分:
def self.create_with_omniauth(auth_hash)
create! do |auth|
auth.provider = auth_hash["provider"]
auth.uid = auth_hash["uid"]
auth.token = auth_hash["credentials"]["token"]
end
end
当遇到该问题时,它将尝试在create!
没有auth.user
对象存在的情况下失败。这是来自sessions
控制器的相关代码:
#-- Spectically, the line below
authentication = Authentication.find_by_provider_and_uid(auth_hash["provider"], auth_hash["uid"]) || Authentication.create_with_omniauth(auth_hash)
#-- More code, for context
if authentication.user
user = authentication.user
authentication.update_token(auth_hash)
@next = root_url
@notice = "Signed in!"
else
user = User.create_with_auth_and_hash(authentication,auth_hash)
@next = edit_user_path(user)
@notice = "User created - confirm or edit details..."
end
要点我唯一想念的就是他Authentications
桌子的结构。使用找到的上下文线索,创建了此表:
def change
create_table :authentications do |t|
t.string :provider
t.string :uid
t.string :token
t.references :user, foreign_key: true
t.timestamps
end
end
如果需要更多信息,我将尽力提供
在Rails 5中,默认情况下要求属居于http://blog.bigbinary.com/2016/02/15/rails-5-makes-belong-to-association-required-by-default.html,因此您将获得一个没有它的验证错误。
在此示例中,您尝试创建Authentication
不带的对象User
,这就是为什么您收到“验证失败:用户必须存在”的原因。
如果您确实想在没有用户的情况下创建身份验证对象,则应该可以使用:
class Authentication < ActiveRecord::Base
belongs_to :user, optional: true
end
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句