2011-06-02 30 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 
相關問題