6

私はOmniAuth railscastsに従っており、railscastに示されているように、devise + twitterの代わりにauthlogic + facebookで同じことを実装しようとしています。

私の理解は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ユーザーはまだ認証を受けていないため、nil です。

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 に答える