0

私の User モデルには次のものがあります。

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 calling User record from Friends model )。 )。そして、なぜただ行うのですか:

 User.friends 

空の配列を返しますか?

4

1 に答える 1

5

メソッドpluckを試してください:

User.first.friends.pluck(:name)

メソッドを使用firstして、テーブルから 1 つのオブジェクトを取得する必要があります。ユーザーは、多くのユーザーがいるテーブルです。

于 2012-09-16T01:40:05.760 に答える