2011-06-02 33 views
6

我正在关注OmniAuth railscasts并试图用authlogic + facebook实现相同的代替devise + twitter,如railscast中所示。has_many返回一个数组而不是ActiveRecord类

也许我的理解has_many仍然不够好,但在railscasts瑞安有following codeAuthenticationsController

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_uidnil对象上。

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

+0

您确定您使用的是Rails 3,还是您使用的是早期版本的Rails? – 2011-06-02 19:09:38

+0

积极的关于它的轨道3.昨晚有这个问题,我想我会问在这里,我再次在家里解决它。我的来源可能有问题。但不应该'has_many'带回数组? – Omnipresent 2011-06-02 19:12:08

+0

在我看来,你已经编码应该工作。你是否证实你不是用你自己的函数(例如在用户类或相关模块中)覆盖认证关系?没有看到更多的代码,这是我所能想到的。 – 2011-06-02 19:38:20

回答

5

阵列实际上是一个AssociationProxy实例,它代表所有方法调用到内部对象,该对象是在has_many关联的情况下的阵列(也参见this question)。这意味着你应该能够调用像find_or_create_by_provider_and_uid这样的魔术方法,以及范围等就可以了。

我发现这个问题,因为我碰上了一个类似的问题:由于某种原因,我不能打电话ActiveRecord::Relation#klass找出模型类:

post.comments.klass # => NoMethodError 

但通过调用relation第一,你可以得到一个正常的ActiveRecord::Relation实例:

post.comments.relation.klass # => Comment 
相关问题