2016-06-28 3 views
1

私はusers have_many:recommendationsがある場所のプロジェクトを持っています。ユーザーもhas_manyのフォロワーとの接続を介して、以下:Rails:ユーザーhas_many:おすすめ:他のユーザーから

has_many :recommendations 
has_many :followers, :class_name => 'Connection', :foreign_key => 'user_id' 
has_many :following, :class_name => 'Connection', :foreign_key => 'follower_id' 

ユーザーが勧告を作成すると、信者がその勧告にアクセスすることができるはずです。

したがって、次のユーザーをフォローすることができます。のユーザーがフォローしているユーザーからのおすすめを取得するには、

ActiveRecordでこれを行うにはどうしたらいいですか?

+1

をするだけbr3ntの答えに追加します。関連のドキュメントを見てください。あなたが必要としているものは何ですか?http://guides.rubyonrails.org/association_basics.html#the-has-many-through-association –

答えて

1

sourceオプションを使用してスルーで使用する関連付けを指定できます。他のクラスのアソシエーションの名前を渡すだけです。

docs

sourceオプション次のように説明します

:sourceオプションがhas_many :through関連付けのためにソース関連名を指定します。ソースアソシエーションの名前をアソシエーション名から自動的に推測できない場合は、このオプションを使用する必要があります。

このような何か作業をする必要があります:

class User 
    has_many :followed_users, :through => :following, :source => :user class_name: User 

    has_many :followed_recommendations, :through => :followed_users, :source => :recommendations, class_name: Recommendation 
end 
関連する問題