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 %>
返回的名称始终是源用户的名称,而不是目标朋友的名称。
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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
好的,我已经解决了:将 User 下的第二个条目更改为:
我仍然不确定问题中的代码是否有一些不需要的内容?
Okay, I've solved it: change the second entry under User to:
I'm still not sure if the code in the question has some unneeded crud in there?