1

ユーザを接続するユーザFriendship (user1_id, user2_id)を作成する必要があります。Howto構造のレールユーザーフレンドシップモデル?

友人関係が両方向に進むにつれて、すべてのユーザー/友人に2つのレコードを作成する必要はありません。

class Friendship < ActiveRecord::Base 
    belongs_to :user1 
    belongs_to :user2 

    after_create :create_mirror! 
    after_destroy :destroy_mirror! 

    validate :does_not_exist 

    def mirror_record 
     Friendship.where(:user1_id => user2.id, :user2_id => user1.id).first 
    end 

    private 

    def does_not_exist 
     errors.add(:base, 'already exists') if Friendship.where(:user1_id => user1.id, :user2_id => user2.id) rescue nil 
    end 

    def create_mirror! 
     Friendship.create(:user1 => user2, :user2 => user1) 
    end 

    def destroy_mirror! 
     mirror_record.destroy if mirror_record 
    end 
end 

答えて

0

これはコードスニペットがうまくいくか、あなたにインスピレーションを与えるでしょう。それはamistad宝石からです。

class User 
    has_many :friendships 
    has_many :invited, :through => :friendships, :source => :friend 
    has_many :invited_by, :through => :inverse_friendships, :source => :user 

    def friends 
    self.invited + self.invited_by 
    end 

class Friendships 
    belongs_to :user 
    belongs_to :friend, :class_name => "User", :foreign_key => "friend_id" 

コントローラでは、user.friendsのように書くとすべての友人を取得できます。

+0

私がやりたいことは、最高の唯一の解決策である、ミラーリングの記録を持たない悪夢です。 –

0

あなただけの友情ごとに1つのレコードを必要とする必要があります。 私のソリューションは、レコードをミラーリングすることだったややシンプル

# User.rb 
has_many :friendships 
has_many :friends, :through => :friendships, :class_name => "User" 

EDITを持ちながらので、あなたはこれを行うだろうか

Friendshipクラスには2つの属性があり、それぞれが友人の1人を指しています。

class Friendship 
    belongs_to user1, :class_name => "User" 
    belongs_to user2, :class_name => "User" 

...そして、あなたのテーブルには、 "持っているし、多くに属し、" 関係(HABTM)としてこれが呼ばれた...のRails 2.xで

friendship_id | user1_id | user2_id 
----------------------------------- 

です。

は、私はあなたが、明示的belongs_to文ごとにクラス名を指定する必要が信じている彼らは、そのようにあなたが両方のフィールドを親レコードの同じタイプ(User)の両方のポイントを呼び出すことはできませんのでuser - あなたを何とか名前を区別しなければなりません。

+0

これは 'Friendship'モデルを動作させますが、' User' HABTM関係はまだ動作しません。 ':source1'は':game1'または ':game2'という1つの値しか持てないので、' User.first.friends << User.last'や 'User.first.friends'を呼び出すことはできません。 –

+0

私が間違っていると私を訂正してください。しかし、has_many:friendshipsとhas_many:friends、:through =>:friendshipsは重複していませんか?たぶん私は何が起こるかを見るためにテストプロジェクトをスピンアップする必要があります。 – jefflunt