1

我有一个用户模型/表和一个朋友模型/表。users 表有一个 uid 列,用于存储用户的 Facebook uid。朋友表存储他们的 Facebook 朋友(由 user_id 列关联)。

如何查询在 users 表中有帐户的特定用户的所有朋友?换句话说 - 我希望为用户 13 的已注册朋友(存在于 users 表中)返回用户模型。

4

3 回答 3

1

我的相同问题的模型

class User < ActiveRecord::Base
    has_many :friendships
    has_many :friends, through: :friendships
    # ...
end

class Friendship < ActiveRecord::Base
    belongs_to :user
    belongs_to :friend, :class_name => 'User', :foreign_key => 'friend_id', :primary_key => 'facebook_id'
end
于 2013-06-12T11:16:08.347 回答
0

如果我有模型:

class User < ActiveRecord::Base
  attr_accessible :name, :uid
  has_many :friends
end

class Friend < ActiveRecord::Base
  attr_accessible :uid
  belongs_to :user
  belongs_to :account, foreign_key: 'uid', primary_key: 'uid', class_name: 'User'
end

那么我可以这样做:

u=User.create(name: 'Alice', uid: 'fb1')
u2=User.create(name: 'Bob', uid: 'fb2')
u.friends.create(uid: 'fb2') # add Bob as friend
u.friends.create(uid: 'fb9') # add someone as friend

现在

u.friends # gives all friends
  Friend Load (0.3ms)  SELECT "friends".* FROM "friends" WHERE "friends"."user_id" = 4
=> [#<Friend id: 3, user_id: 4, uid: "fb2">, #<Friend id: 4, user_id: 4, uid: "fb9">]

u.friends.joins(:account) # only friends having an account
  Friend Load (0.2ms)  SELECT "friends".* FROM "friends" INNER JOIN "users" ON "users"."uid" = "friends"."uid" WHERE "friends"."user_id" = 4
=> [#<Friend id: 3, user_id: 4, uid: "fb2">]

whileincludes不进行内部连接并给所有朋友:

u.friends.includes(:account)
  Friend Load (0.2ms)  SELECT "friends".* FROM "friends" WHERE "friends"."user_id" = 4
  User Load (0.2ms)  SELECT "users".* FROM "users" WHERE "users"."uid" IN ('fb2', 'fb9')
=> [#<Friend id: 3, user_id: 4, uid: "fb2">, #<Friend id: 4, user_id: 4, uid: "fb9">]
于 2013-06-12T06:43:07.370 回答
0

假设您感兴趣的用户由以下内容引用@user

User.joins("inner join friends on friends.uid = users.uid")
.where("friends.user_id = ?", @user.id)

可能有一种更“有条理”的方法可以更好地利用 arel。

于 2013-06-12T06:29:50.103 回答