ActiveRecord:创建与其自身的一对多关系

发布于 2024-08-05 20:27:42 字数 987 浏览 1 评论 0原文

我正在建立一个社交网站。我有一张用户表。每个用户可以有许多其他用户作为朋友,所以我有第二个表朋友:

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

返回的名称始终是源用户的名称,而不是目标朋友的名称。

I'm building a social networking website. I have a table of Users. Each user can have a number of other users as friends, so I have a second table Friends:

user_id
friend_id

Based on this answer I'm trying to create the relationships. I have,

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

and

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

When I try and use the tables with this in my view:

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

the names returned are always those of the source user, rather than the target friend.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

云归处 2024-08-12 20:27:42

好的,我已经解决了:将 User 下的第二个条目更改为:

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

我仍然不确定问题中的代码是否有一些不需要的内容?

Okay, I've solved it: change the second entry under User to:

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

I'm still not sure if the code in the question has some unneeded crud in there?

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文