同时查找包含两个ID的记录

时间:2017-09-26 08:41:21

标签: ruby-on-rails ruby activerecord

我有模特:

用户

"App-Prefs:root=\(Bundle.main.bundleIdentifier!)"

UsersConversation

class User < ActiveRecord::Base
  has_many :users_conversations, dependent: :destroy
  has_many :conversations, through: :users_conversations, dependent: :destroy
end

会话

class UsersConversation < ActiveRecord::Base
  belongs_to :conversation
  belongs_to :user
end

我需要创建查询以通过其ID获取两个已知用户之间的联合对话。我有这个

class Conversation < ActiveRecord::Base
  has_many :users_conversations, dependent: :destroy
  has_many :users, through: :users_conversations
end

但它找到的对话是Conversation.left_joins(:users).where(users: { id: [current_user.id, params[:user_id]]}).first 中的任何一个,所以我总是得到相同的对话,[current_user.id, params[:user_id]],但这是错误的。我认为这是因为current_user像OR一样工作,但我需要AND。谢谢。

1 个答案:

答案 0 :(得分:0)

评论中提到的答案不正确。请不要参考。

尝试使用

Conversation.left_joins(:users).find_by("users.id IN(?)", [current_user.id, params[:user_id]]})

Haven实际上已经尝试过,但这应该可行。如果您遇到错误,请告诉我。

此外,请改用find_byModel.where(condition).first。使用后者是铁轨中的坏习惯和惯例。

解释:当您必须找到字段与数组匹配的记录时,即您需要将此字段的值设置为数组时,应使用SQL的IN运算符。喜欢

SELECT * FROM Customers WHERE Country IN ('Germany', 'France', 'UK');

相关问题