【问题标题】:ActiveRecord: creating a one-to-many relationship back to itselfActiveRecord:创建一对多的关系回到自己
【发布时间】:2009-09-26 19:42:22
【问题描述】:

我正在建立一个社交网站。我有一个用户表。每个用户可以有多个其他用户作为朋友,所以我有第二个表 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 %>

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

【问题讨论】:

    标签: ruby-on-rails database activerecord relationships


    【解决方案1】:

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

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

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

    【讨论】:

      猜你喜欢
      • 2013-03-15
      • 2011-07-09
      • 1970-01-01
      • 1970-01-01
      • 2016-03-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多