问题描述
我有这个聊天服务的模型设计:
class ChatRoom < ApplicationRecord
has_many :chat_room_infos,dependent: :destroy
has_many :employees,through: :chat_room_infos,source: :chattable,source_type: Employee.name,dependent: :destroy
has_many :employers,source_type: Employer.name,dependent: :destroy
end
class ChatRoomInfo < ApplicationRecrod
belongs_to :chat_room
belongs_to :chattable,polymorphic: true
has_many :employees,through: :chat_room # Employees in the same chat room
has_many :employers,through: :chat_room # Employers in the same chat room
end
我想通过参与者数组(包含任意数量的ChatRoom
和Employee
)找到Employer
为了做到这一点,我首先要找到参与者的ChatRoomInfo
:
chat_room.rb
scope :where_participants_in,->(users) { joins(:chat_room_infos).merge(ChatRoomInfo.where(chattable: users)) }
产生以下查询:
> ChatRoom.where_participants_in([Employee.find(8),Employer.find(3)])
SELECT
`chat_rooms`.*
FROM
`chat_rooms`
INNER JOIN `chat_room_infos` ON `chat_room_infos`.`chat_room_id` = `chat_rooms`.`id`
WHERE
( `chat_room_infos`.`chattable_type` = 'Employee' AND `chat_room_infos`.`chattable_id` = 8
OR `chat_room_infos`.`chattable_type` = 'Employer' AND `chat_room_infos`.`chattable_id` = 3 )
然后,我想通过匹配的计数来查询 ChatRoom
。在这种情况下,如果匹配的计数正好是 2,那么它就是我想要的 ChatRoom
:
chat_room.rb
scope :where_participants_count,->(users) { where_participants_in(users).count }
> ChatRoom.where_participants_count([Employee.find(8),Employer.find(3)])
SELECT
COUNT(*)
FROM
`chat_rooms`
INNER JOIN `chat_room_infos` ON `chat_room_infos`.`chat_room_id` = `chat_rooms`.`id`
WHERE
(
`chat_room_infos`.`chattable_type` = 'Employee'
AND `chat_room_infos`.`chattable_id` = 8
OR `chat_room_infos`.`chattable_type` = 'Employer'
AND `chat_room_infos`.`chattable_id` = 3)
=> 2 # the first result is two
所以我需要做的就是通过这个 select sql 查询 ChatRoom
。
我尝试过这样的事情:
chat_room.rb
scope :where_participants,->(users) { where(where_participants_count(users).eq(users.count)) }
但我收到此错误:
NoMethodError(2:Integer 的未定义方法 `eq')
我该如何解决这个问题?这是我想使用 activerecord 方法获取的示例查询:
SELECT * FROM `chat_rooms` WHERE (SELECT
COUNT(`chat_rooms`.`id`) AS count
FROM
`chat_rooms`
JOIN `chat_room_infos` ON `chat_room_infos`.`chat_room_id` = `chat_rooms`.`id`
WHERE
(`chat_room_infos`.`chattable_type` = 'Employer' AND `chat_room_infos`.`chattable_id` = 3) OR
(`chat_room_infos`.`chattable_type` = 'Employee' AND `chat_room_infos`.`chattable_id` = 8)) = 2
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)