2011-09-23 58 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