私には友情モデルがあり、新しい友情ごとに 2 つの新しいレコードを作成します。
- User1 と Friend1
- フレンド1とユーザー1
友達、友達、保留中の友達など、すべての標準スタッフを取得できます...共通の友達、友達の友達を取得しようとすると、状況が複雑になります...
今のところ、共通の友情を得るために、私は次のようなものを使用しています:
has_many :common_friendships, :class_name => 'Friendship', :conditions=>'friendships.user_id = #{self.id}' do
def common_with(friend)
joins("inner join friendships fl2 on friendships.friend_id = fl2.user_id").where("fl2.friend_id = #{friend.id}")
end
end
finder_sql
また、次のような完全なクエリを使用できます。
select distinct *
from friendships fl1
inner join friendships fl2 on fl1.friend_id = fl2.user_id
where fl1.user_id = 1 and fl2.friend_id = 2
Rails 3でエレガントな方法でそれを行うにはどうすればよいですか?