2016-12-09 7 views
0

Ruby ORMに取り組んでおり、多対多の構文と多相を理解しようとしています。 これまでのアクティブレコードの関係があります。Ruby ORM多相関係、アクティブレコード

class Association < ActiveRecord::Base 
    belongs_to :user 
    belongs_to :friend, class_name: "User" 
end 

class User < ActiveRecord::Base 
    has_many :associations 
    has_many :friends, through: :associations 
end 

私はそれらの友人が複数のユーザーに関連付けられている場合、ユーザーごとの友人のリストを取得するように見えることはできません。言い換えれば、一部のユーザーには友人がいて、これらの友人には複数のユーザー関連があることもあります。

答えて

0

まず、これらは多型関連ではありません。あるモデルがCommentモデルのような多くのモデルに属している場合、多態的な関連付けを使用します。ユーザーは、プロジェクト上の画像上の投稿にコメントを付けることができるので、Commentモデルはこれらのいずれかに属している可能性があります。そこで、多態性の関連付けを使用します。それについてもっと知るためにRead here

あなたが求めていることは、Inverse Friendsについてです。ここでは、その実装方法を示します。

class User < ActiveRecord::Base 
    has_many :associations 
    has_many :friends, through: :associations 
    has_many :inverse_associations, class_name: "Association", foreign_key: :friend_id 
    has_many :inverse_friends, through: :inverse_associations, source: :user 
end 

class Assocation < ActiveRecord::Base 
    belongs_to :user 
    belogns_to :friend, class_name: 'User' 
    belongs_to :inverse_friend, class_name: 'User', foreign_key: :friend_id 
end