Rails 3如何减少查询

时间:2012-09-12 01:14:29

标签: ruby-on-rails-3 activerecord

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

我仍然很欣赏如何减少或优化这些查询。

1 个答案:

答案 0 :(得分:1)

尝试使用includes代替joins来避免n + 1问题 Railscast#181 Ryan Bates,http://railscasts.com/episodes/181-include-vs-joins?view=asciicast,以简单的方式解释了这种差异。