###前提・実現したいこと
Ruby on Railsでメッセージアプリを作っています
モデルの検索から、条件に応じてモデルを操作したいのですが、
モデルの検索が上手くできません。
Conversation, User は中間テーブルを通して多対多の関係です。
ruby
1 2 Conversation.joins(:users).where(users: {id: [current_user.id,params[:friend_id].to_i]})
"{id:.."のところ、 []でくくってしまうと、OR検索になってしまい、current_user.id,friend_id のどちらかがあれば if 以下が実行されてしまいます。
そうではなく、AND検索で、current_user.id,params[:friend_id] のどちらも入ったconversation を取り出したいです。
###該当のソースコード
ruby
1class ConversationsController < ApplicationController 2 3 def find_or_new_conv 4 if q = Conversation.joins(:users).where(users: {id: [current_user.id,params[:friend_id].to_i]}) 5 redirect_to action: :show, id: q.id 6 else 7 con = Conversation.create 8 con.users << current_user 9 con.users << User.find(params[:friend_id].to_i) 10 redirect_to action: :show, id: con.id 11 end 12 end
###試したこと
ruby
1Conversation.joins(:users).where(users: {id:current_user.id}).where(users: {id:params[:friend_id].to_i]})
とすれば、AND検索ができるはずですが、空の配列が返ってきてしまいます。
###補足情報(言語/FW/ツール等のバージョンなど)
Rails 5.0.0.1
回答1件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。