has_many 返回一个数组而不是 ActiveRecord 类

发布于 2024-11-11 15:12:09 字数 1054 浏览 4 评论 0原文

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

也许我对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 不是应该返回一个数组吗?

我得到的错误是我在 nil 对象上调用 find_or_create_by_provider_and_uid

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

I am following OmniAuth railscasts and trying to implement the same with authlogic + facebook instead of devise + twitter as shown in the railscast.

Maybe my understanding of has_many still isn't good but in the railscasts ryan has the following code in 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

In my implementation current_user.authentications returns an array [] how can I call find_or_create_by_provider_and_uid on an array?

Is my implementation wrong? Isn't has_many suppose to return an array?

Error I get is that I am calling find_or_create_by_provider_and_uid on a nil object.

current_user.authentications is nil well because the user does not have any authentications yet.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

梓梦 2024-11-18 15:12:09

该数组实际上是一个 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

The array is actually an AssociationProxy instance, which delegates all method calls to the internal object, which is an array in the case of a has_many association (also see this question). This means you should be able to call magic methods like find_or_create_by_provider_and_uid, as well as scopes etc. on it just fine.

I found this question because I stumbled over a similar problem: for some reason I couldn't call ActiveRecord::Relation#klass to find out the model class:

post.comments.klass # => NoMethodError

But by calling relation first you can get a normal ActiveRecord::Relation instance:

post.comments.relation.klass # => Comment
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文