c = Conversation.joins(:messages).random
>> Conversation Load (8.1ms) SELECT `conversations`.* FROM `conversations` INNER JOIN `messages` ON `messages`.`conversation_id` = `conversations`.`id` ORDER BY created_at DESC, RAND() LIMIT 1
数数:
c.messages.count
>> (5.7ms) SELECT COUNT(*) FROM `messages` WHERE `messages`.`conversation_id` = 74
长度:
c.messages.length
>> Message Load (1.2ms) SELECT `messages`.* FROM `messages` WHERE `messages`.`conversation_id` = 82
如何不执行上述附加查询?我以为我已经使用 INNER JOIN 加入了随机对话的消息,但是执行了一个新查询来计算这些结果?
第二个问题是尝试获取具有特定 user_id 的所有加入消息:
u = User with id 27 # has messages in 'c' results above
c.messages.where('user_id = ?', u.id).all
>> Message Load (5.3ms) SELECT `messages`.* FROM `messages` WHERE `messages`.`conversation_id` = 82 AND (user_id = 27)
我使用 select 来执行此操作而无需其他查询:
c.messages.select { |msg| msg.user_id == u.id }
>> returns messages without query logged
我仍然很感激我可以如何减少或优化这些查询。