0

在我的用户模型中,我有以下内容:

class User < ActiveRecord::Base
  has_many :friendships, dependent: :destroy
  has_many :friends, :class_name => "User", :foreign_key => "friend_id"

  has_many :pending_friends, 
   :through => :friendships, 
   :conditions => "status = 'pending'", 
   :foreign_key => "user_id", 
   :source => :friend

  has_many :requested_friends, 
   :through => :friendships,
   :source => :friend, 
   :conditions => "status = 'requested'"

  def friends
    direct_friends | inverse_friends
  end

在我的友谊模型中,我有以下内容:

class Friendship < ActiveRecord::Base
 belongs_to :user
 belongs_to :friend, :class_name => "User", :foreign_key => "friend_id"

在我看来,我创建了一个包含每个用户朋友的数组,如下所示。此代码工作并使用来自朋友的“用户”数据库模型属性的所有数据填充数组。

  User.first.friends

但是,我希望能够调用用户朋友的名字。那么,例如,我不应该能够做这样的事情吗?

    User.first.friends.map(&:name)

如何获取仅包含朋友姓名而不是所有朋友用户属性的数组?如果有人能告诉我为什么使用 .first ,我也将不胜感激(我从这里得到:Rails calls User record from Friends model),因为它不只是获取用户朋友的第一个实例(它获取所有实例)。为什么只是这样做:

 User.friends 

返回一个空数组?

4

1 回答 1

5

尝试方法pluck

User.first.friends.pluck(:name)

您应该使用first方法从表中检索一个对象。User 是一个有很多用户的表。

于 2012-09-16T01:40:05.760 回答