ging/mailboxer — Issue #13: Multiple queries to get sender
Author: Gazler
Created: 2011-12-08 16:20:12+00:00
State: open

Hi,

This gem appears to do most of the things I would expect for messaging which is great, however, a common feature of message inboxes is to get the sender along with subject and date.

To get the sender I am using originator (assuming one-to-one messaging for the moment)

I have the following code:

def inbox
response = []
current_user.mailbox.inbox.each do |i|
response << MessagePresenter.new(i, current_user)
end
#...snip...
end

And my presenter looks like this:

def as_json(*)
sender = @message.originator
# ...snip...
end

The issue here is the number of queries this does: (output from a call that retrieves 4 messages)

> Conversation Load (0.2ms) SELECT DISTINCT conversations.* FROM "conversations" INNER JOIN "notifications" ON "notifications"."conversation_id" = "conversations"."id" AND "notifications"."type" IN ('Message') INNER JOIN "receipts" ON "receipts"."notification_id" = "notifications"."id" WHERE "notifications"."type" = 'Message' AND "receipts"."receiver_id" = 1 AND "receipts"."receiver_type" = 'User' AND "receipts"."mailbox_type" = 'inbox' AND "receipts"."trashed" = 'f' ORDER BY conversations.updated_at DESC
Message Load (0.2ms) SELECT "notifications".* FROM "notifications" WHERE "notifications"."type" IN ('Message') AND "notifications"."conversation_id" = 5 ORDER BY created_at LIMIT 1
User Load (0.1ms) SELECT "users".* FROM "users" WHERE "users"."id" = 2 LIMIT 1
Message Load (0.1ms) SELECT "notifications".* FROM "notifications" WHERE "notifications"."type" IN ('Message') AND "notifications"."conversation_id" = 4 ORDER BY created_at LIMIT 1
CACHE (0.0ms) SELECT "users".* FROM "users" WHERE "users"."id" = 2 LIMIT 1
Message Load (0.1ms) SELECT "notifications".* FROM "notifications" WHERE "notifications"."type" IN ('Message') AND "notifications"."conversation_id" = 3 ORDER BY created_at LIMIT 1
CACHE (0.0ms) SELECT "users".* FROM "users" WHERE "users"."id" = 2 LIMIT 1
Message Load (0.1ms) SELECT "notifications".* FROM "notifications" WHERE "notifications"."type" IN ('Message') AND "notifications"."conversation_id" = 2 ORDER BY created_at LIMIT 1
CACHE (0.0ms) SELECT "users".* FROM "users" WHERE "users"."id" = 2 LIMIT 1

Since this is such a common thing, shouldn't the sender be included with the request? If not, how can I reduce this to fewer queries?

Regards,
Gazler.