has_many 返回一个数组而不是 ActiveRecord 类
我正在关注 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 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
该数组实际上是一个
AssociationProxy
实例,它将所有方法调用委托给内部对象,在has_many
关联的情况下,该内部对象是一个数组(另请参阅 这个问题)。这意味着您应该能够调用诸如find_or_create_by_provider_and_uid
之类的魔术方法以及作用域等。我发现这个问题是因为我偶然发现了一个类似的问题:出于某种原因,我无法调用
ActiveRecord::Relation#klass
来找出模型类:但是通过调用
relation
首先你可以得到一个普通的ActiveRecord::Relation
实例:The array is actually an
AssociationProxy
instance, which delegates all method calls to the internal object, which is an array in the case of ahas_many
association (also see this question). This means you should be able to call magic methods likefind_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:But by calling
relation
first you can get a normalActiveRecord::Relation
instance: