【发布时间】:2011-09-23 00:31:23
【问题描述】:
我已经建立了一个简单的Friend 模型,它允许Users 拥有多个朋友。看起来是这样的:
class Friend < ActiveRecord::Base
belongs_to :user
class User < ActiveRecord::Base
has_many :friends
每个好友记录只有一个id、user_id 和friend_id。 user_id 是它所属的用户的 id,friend_id 是他们正在结交的用户的 id。
这是我的问题
我不太确定如何显示特定用户的朋友列表。 @user.friends 会给我他们拥有的所有朋友记录的列表,但不是这些朋友的用户帐户。
例如,我正在尝试为friends 控制器构建一个show 页面:
class FriendsController < ApplicationController
def show
@user = current_user
end
SHOW.HTML.ERB
<% if @user.friends.count > 0 %>
<% @user.friends.each do |friend| %>
<div class="entry">
<%= friend.username %>
这不起作用,因为在这种情况下friend 没有username。我需要在我的控制器中做这样的事情:
@friend = User.find_by_id(friend.friend_id)
但我不确定在@user.friends 循环中我会如何称呼它。任何想法表示赞赏。如果我需要更清楚,请告诉我。
更新
我已经像这样更新了我的User 模型:
has_many :friends, :include => :user
has_many :friended_users, :through => :friends, :source => :user, :uniq => true
但是,当我运行@user.friended_users 时,它给了我user_ids(与@user 相同)而不是friend_ids。
如何调整这种关系,使其链接到 friend_id 而不是 user_id?
我想得越多,我想我可能一开始就没有正确建立关系。也许User 应该是has_many :users, through => 'friends',但这没有任何意义......
更新 我根据@twooface 的输入更新了我的模型:
class User < ActiveRecord::Base
has_many :friendships
has_many :friends, :through => :friendships
class Friendship < ActiveRecord::Base
belongs_to :user
belongs_to :friend, :class_name => 'User'
class Friend < ActiveRecord::Base
has_many :friendships
has_many :users
我只是不确定我的 Friends 表应该是什么样子。我认为它应该有一个主键和一个user_id?如果我创建一个友谊和朋友记录,我可以做friendship.user 和friendship.friend 并得到正确的结果,但user.friends 给了我一个空哈希...
【问题讨论】:
标签: ruby-on-rails-3 model