2009-09-26 98 views
1

我正在建立一个社交网站。我有一张用户表。每个用户都可以有许多其他用户的朋友,所以我有第二个表友:基于这个答案我试图创建的关系ActiveRecord:创建一个一对多的关系

user_id 
friend_id 

。我有,

class User < ActiveRecord::Base 
    has_many :friends, :dependent => :destroy 
    has_many :users, :through => :friends 

    has_many :source_friend, :class_name => "Friend", :foreign_key => "friend_id", :dependent => :destroy 
    has_many :source_users, :class_name => "User", :through => :friend_id 
    ... 

class Friend < ActiveRecord::Base 
    belongs_to :user 
    belongs_to :source_friend, :class_name => "User", :foreign_key => "friend_id" 
end 

当我尝试使用这个表中我的观点:

<% @user.users.each do |friend| %> 
    <% if friend.status == User::ACTIVE %> 
    <p> 
     <%= link_to h(friend.name), :controller => "user", :id => h(friend.name)%> 
    </p> 
    <% end %> 
<% end %> 

返回的名字总是那些源用户的,而比目标朋友。

回答

0

好啦,我已经解决了这个问题:在用户更改第二项:

has_many :users, :through => :friends, :source => :source_friend 

我仍然不知道,如果在问题的代码有一些不必要的CRUD在那里?