1

我需要創建一個連接用戶的用戶Friendship (user1_id, user2_id)模型。如何構建rails用戶友誼模型?

我想避免爲每個用戶/朋友創建兩個Friendship記錄,因爲友誼是雙向的。

你會如何做,所以雖然具有稍顯簡單

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

編輯 我的解決辦法,以反映記錄:

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

您應該只需要每友誼的一個記錄。 Friendship類只有兩個屬性,每個屬性指向一個朋友。

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

...和你的表...

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

在Rails 2.x中這被稱爲 「擁有屬於一對多」 的關係(HABTM)。

我相信你會爲每個belongs_to語句來顯式地指定類名,因爲它們都指向同一類型的父記錄的(一個User),因此你不能說這兩個領域user - 你必須以某種方式來區分它們。

+0

這使得「Friendship」模型可以工作,但User' HABTM關係仍然不起作用。您不能將'User.first.friends << User.last'或甚至User.first.friends調用爲':source'只能有一個值,':game1'或':game2'。 –

+0

糾正我,如果我錯了,但不是'has_many:friendships'和'has_many:friends,:through =>:友誼'多餘?也許我必須啓動一個測試項目來看看會發生什麼。 – jefflunt