使用 Rails 5,我正在尝试实现 Omniauth-Facebook 和 Clearance 以进行用户身份验证。
注意:我的代码和这个 Gist完全一样
我已经让它大部分工作了。然而,当使用 Facebook 进行注册时(即用户从未访问过该站点),Rails 会抛出一个错误,说Validation failed: User must exist
. 我已将问题范围缩小到 Gist 中的这个块:
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
我在 Gist 中唯一遗漏的是他的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
如果需要更多信息,我会提供我能提供的