6

我正在关注OmniAuth railscasts并尝试使用 authlogic + facebook 而不是如 railscast 中所示的 devise + twitter 来实现相同的功能。

也许我的理解has_many仍然不好,但在 railscasts ryan 中有以下代码AuthenticationsController

  def create
    auth = request.env["rack.auth"]
    current_user.authentications.find_or_create_by_provider_and_uid(auth['provider'], auth['uid'])
    flash[:notice] = "Authentication successful."
    redirect_to authentications_url
  end

在我的实现中current_user.authentications返回一个数组[]我如何调用find_or_create_by_provider_and_uid一个数组?

我的实施错了吗?不has_many应该返回一个数组吗?

我得到的错误是我正在调用find_or_create_by_provider_and_uid一个nil对象。

current_user.authentications很好,因为用户还没有任何身份验证。

4

1 回答 1

5

数组实际上是一个AssociationProxy实例,它将所有方法调用委托给内部对象,在关联的情况下它是一个数组has_many(另见这个问题)。这意味着您应该能够在其上调用魔术方法,如find_or_create_by_provider_and_uid, 以及作用域等。

我发现这个问题是因为我偶然发现了一个类似的问题:由于某种原因,我无法打电话ActiveRecord::Relation#klass来找出模型类:

post.comments.klass # => NoMethodError

但是通过先调用relation,您可以获得一个正常的ActiveRecord::Relation实例:

post.comments.relation.klass # => Comment
于 2012-01-20T00:02:32.400 回答