2011-09-23 55 views
0

我建立了一個簡單的Friend模型,它允許Users有多個朋友。下面是一個樣子:Rails從朋友模型

class Friend < ActiveRecord::Base 
    belongs_to :user 

class User < ActiveRecord::Base 
    has_many :friends 

每個朋友記錄只是有一個iduser_idfriend_iduser_id是它所屬用戶的ID,而friend_id是他們正在結交的用戶的ID。

這是我的問題 我不太清楚如何顯示特定用戶的朋友列表。 @user.friends會給我一個他們擁有的所有朋友記錄的列表,但不會列出這些朋友的用戶帳戶。

舉例來說,我試圖建立一個show頁的friends控制器:

class FriendsController < ApplicationController 
def show 
    @user = current_user 
end 

SHOW.HTML.ERB

<% if @user.friends.count > 0 %> 
    <% @user.friends.each do |friend| %> 
    <div class="entry"> 
     <%= friend.username %> 

這不起作用,因爲friend在這種情況下不有username。我需要做這樣的事情在我的控制器:

@friend = User.find_by_id(friend.friend_id) 

但我不知道我怎麼會說這就是我在@ user.friends循環圖。任何想法讚賞。讓我知道如果我需要更清楚。

UPDATE 我已經更新了我User模型像這樣:

has_many :friends, :include => :user 
has_many :friended_users, :through => :friends, :source => :user, :uniq => true 

然而,當我運行@user.friended_users它給我user_id秒(這是一樣的@user),而不是friend_id小號。

如何調整關係,以便鏈接到friend_id而不是user_id

我越想到它,我想我可能沒有正確地建立關係。也許User應該has_many :users, through => 'friends',但並沒有真正意義......

UPDATE 基於@ twooface輸入我已經更新我的模型:

class User < ActiveRecord::Base 
    has_many :friendships 
    has_many :friends, :through => :friendships 

class Friendship < ActiveRecord::Base 
    belongs_to :user 
    belongs_to :friend, :class_name => 'User' 

class Friend < ActiveRecord::Base 
    has_many :friendships 
    has_many :users 

我只是不知道我的朋友表應該是什麼樣子。我認爲它應該有一個主鍵和一個user_id?如果我創建了友誼和朋友的記錄,我可以做friendship.userfriendship.friend並得到正確的結果,但user.friends給我一個空哈希...

回答

0

我想你的關係是建立一個有點不對勁。嘗試這樣:

class User < ActiveRecord::Base 
    has_many :friends 
    has_many :friendships 
    has_many :friends, :through => :friendships 

class Friendship < ActiveRecord::Base 
    belongs_to :user 
    belongs_to :friend, :class_name => 'User' 
    # This class has :user_id and :friend_id 

然後一切都會更簡單。每個用戶都會擁有一系列只是用戶的朋友。

User.first.friends 

將返回此用戶朋友的用戶數組。

希望這會有所幫助。

+0

好的。糾正我,如果我錯了,所以Friend類有:user_id和:friend_id,並且Friendship類也有:user_id和:friend_id? –

+0

@twoface,我根據你所說的更新了我的模型,但我不確定朋友應該看起來像什麼(見上面的更新)。我會很感激任何建議;謝謝! –

+0

沒有朋友類(有點,它是User類的一個實例),所以你只有User類的對象和它們之間的友誼對象。 – twooface