1

私はソーシャルネットワーキングウェブサイトを構築しています。ユーザーのテーブルがあります。各ユーザーは他の多くのユーザーを友達として持つことができるので、2 つ目のテーブル Friends:

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 %>

返される名前は、ターゲット フレンドではなく、常にソース ユーザーのものです。

4

1 に答える 1

0

わかりました、解決しました: User の下の 2 番目のエントリを次のように変更します。

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

問題のコードに不要な部分が含まれているかどうかはまだわかりませんか?

于 2009-09-26T22:18:28.973 に答える