私がモデルを持っている場合:
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">]