Railsでクエリを実行する「(xAND y)OR(a ANDb)」を作成する最良の方法は何ですか?
2人のユーザー間でメッセージを返すために次のmessagesメソッドを作成しました。選択は、2人のユーザー間でメッセージを取得することです。つまり、私から彼らへ、そして彼らから私へのメッセージを私に与えます。
それは動作しますが、恐ろしいように見えます。これを書くためのより簡単でより良い方法はありますか?
class Conversation
def initialize(me, them)
@me = me
@them = them
end
def messages
t = Message.arel_table
results = Message.where(
(t[:sender_id].eq(@me.id).and(t[:recipient_id].eq(@them.id))).or(
t[:sender_id].eq(@them.id).and(t[:recipient_id].eq(@me.id)))
)
end
end
注ジミーのおかげで、私は次のようになりました。
class Conversation
def initialize(me, them)
@me = me
@them = them
end
def messages
me_to_them = "sender_id = :my_id AND recipient_id = :their_id"
them_to_me = "sender_id = :their_id AND recipient_id = :my_id"
Message.where(
"#{me_to_them} OR #{them_to_me}",
{:my_id => @me.id, :their_id => @them.id}
)
end
end