Skip to content

Commit

Permalink
use a subquery to speed up the last messages query (#3)
Browse files Browse the repository at this point in the history
* use a subquery to speed up the last messages query
* fix style recommendations from rubocoop
  • Loading branch information
mortbauer authored Apr 12, 2023
1 parent 46d2aae commit fab4b07
Show file tree
Hide file tree
Showing 2 changed files with 8 additions and 1 deletion.
7 changes: 7 additions & 0 deletions plugins/messages/app/models/message.rb
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,13 @@ class Message < ApplicationRecord
.where('private = ? OR sender_id = ? OR message_recipients.user_id = ?', false, user_id, user_id)
.distinct
}
scope :last_readable_for, ->(user, nr) {
user_id = user.try(&:id)
received = MessageRecipient.select(:message_id, :user_id).where(user_id: user_id).limit(nr)

joins("LEFT OUTER JOIN (#{received.to_sql}) sub ON messages.id = sub.message_id")
.where('private = ? OR sender_id = ? OR sub.user_id = ?', false, user_id, user_id)
}

validates_presence_of :message_recipients, :subject, :body
validates_length_of :subject, :in => 1..255
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,5 +3,5 @@
- unless Message.readable_for(current_user).empty?
%section#messages
%h2= t '.messages.title'
= render 'messages/messages', messages: Message.readable_for(current_user).includes(:sender).order('created_at DESC').limit(5), pagination: false
= render 'messages/messages', messages: Message.last_readable_for(current_user,5).includes(:sender).order('created_at DESC').limit(5), pagination: false
%p= raw t '.messages.view_all.text', messages: link_to(t('.messages.view_all.messages'), messages_path), threads: link_to(t('.messages.view_all.threads'), message_threads_path)

0 comments on commit fab4b07

Please sign in to comment.