Rails加入还是包含?

时间:2013-06-12 06:13:23

标签: ruby-on-rails join include

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

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

3 个答案:

答案 0 :(得分: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

答案 1 :(得分:0)

假设您感兴趣的用户被@user引用:

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

有可能采用更“顽固”的方式来更好地利用arel。

答案 2 :(得分: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">]

虽然includes没有进行内部联接并且给所有朋友:

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">]