【问题标题】:Rails calling User record from Friends modelRails 从 Friends 模型中调用用户记录
【发布时间】:2011-09-23 00:31:23
【问题描述】:

我已经建立了一个简单的Friend 模型,它允许Users 拥有多个朋友。看起来是这样的:

class Friend < ActiveRecord::Base
  belongs_to :user

class User < ActiveRecord::Base
  has_many :friends

每个好友记录只有一个iduser_idfriend_iduser_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 =&gt; '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.userfriendship.friend 并得到正确的结果,但user.friends 给了我一个空哈希...

【问题讨论】:

    标签: ruby-on-rails-3 model


    【解决方案1】:

    我认为你们的关系有些不对劲。试试这样的:

    class User < ActiveRecord::Base
      has_many :friends
      has_many :friendships
      has_many :friends, :through => :friendships
    
    class Friendship < ActiveRecord::Base
      belongs_to :user
      belongs_to :friend, :class_name => 'User'
      # This class has :user_id and :friend_id
    

    然后一切都会变得简单。每个用户都会有一系列朋友,他们只是用户。

    User.first.friends
    

    将返回此用户好友的用户数组。

    希望这会有所帮助。

    【讨论】:

    • 好的。如果我错了,请纠正我,所以 Friend 类有 :user_id 和 :friend_id,Friendship 类也有 :user_id 和 :friend_id?
    • @twoface,我已经根据你所说的更新了我的模型,但我只是不确定朋友应该是什么样子(见上面的更新)。我会很感激任何建议;谢谢!
    • 没有 Friend 类(有点,它是 User 类的一个实例),所以你只有 User 类的对象和它们之间的 Friendships 对象。
    猜你喜欢
    • 2016-05-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多