1

使用 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

如果需要更多信息,我会提供我能提供的

4

1 回答 1

4

在 Rails 5 中,belongs_to 默认需要http://blog.bigbinary.com/2016/02/15/rails-5-makes-belong-to-association-required-by-default.html,所以你会得到一个没有它的验证错误。

在此示例中,您尝试创建Authentication没有 的对象User,这就是您得到“验证失败:用户必须存在”的原因。

如果您真的想在没有用户的情况下创建 Authentication 对象,这应该可以:

class Authentication < ActiveRecord::Base
  belongs_to :user, optional: true
end
于 2016-04-03T04:15:17.173 回答