2

在我的模型中,我有:

#models/friend.rb
scope :approved_friend, where(:approved => true)

Rails 控制台输出:

User.find(2).friends
 => [#<Friend id: 18, user_id: 2, approved: true, created_at: "2013-04-23 09:18:59", updated_at: "2013-04-23 09:18:59", friend_id: 1>] 

User.find(2).friends.approved_friend
=> [] 

请注意,输出中的批准是正确的......它变得疯狂的地方在这里:

User.find(1).friends.approved_friend
=> [#<Friend id: 19, user_id: 1, approved: true, created_at: "2013-04-23 09:19:36", updated_at: "2013-04-23 09:19:36", friend_id: 2>] 

我是不是错过了什么?

编辑: 一方面你有这个查询:

SELECT "friends".* FROM "friends" WHERE "friends"."user_id" = 2

 => [#<Friend id: 18, user_id: 2, approved: true, created_at: "2013-04-23 09:18:59", updated_at: "2013-04-23 09:18:59", friend_id: 1>] 

另一方面,你有这个(通过范围查询):

SELECT "friends".* FROM "friends" WHERE "friends"."user_id" = 2 AND "friends"."approved" = 't'
 => []
4

1 回答 1

0

由于 :status 字段位于 Friend 模型中,您可能必须将范围更改为此

范围 :approved_friend, where('friends.approved' => true).includes(:friend)

于 2013-04-23T13:36:25.233 回答