Rails如何根据两个字段查询记录

时间:2011-12-14 01:40:40

标签: ruby-on-rails ruby-on-rails-3

我有一个朋友模型

user_id, friend_id, status (approved, pending, ignored)

我想查询user1&用户2有记录。

user1.id = 10
user2.id = 9

朋友模型可能有

10,9,x
9,10,x

对于这两种组合,我如何编写一个可以查看记录是否存在的rails查询?感谢

1 个答案:

答案 0 :(得分:1)

怎么样:

Friend.where(:user_id => [user.id, self.id], :friend_id => [user.id, self.id], :status => 'x')

转换为SQL将是:

  

“SELECT \”friends \“。* FROM \”friends \“WHERE \”friends \“。\”user_id \“IN(10,9)AND \”friends \“。\”friend_id \“IN( 10,9)AND \“friends \”。\“status \”='x'“

它将使用一个查询返回两个案例:

[#<Friend id: 1, user_id: 10, friend_id: 9, status: 'x', created_at: "2011-06-25 15:09:00", updated_at: "2011-11-01 18:28:50">, #<Friend id: 2, user_id: 9, friend_id: 10, status: 'x', created_at: "2011-06-25 15:11:06", updated_at: "2011-11-01 18:28:50">]