0

I'm using awesome_nested_set for building mail conversations. I have two mailboxes (Inbox and Sent) and now I want to build a proper conversation view. The main goal is select roots that have any descendants in target mailbox and root's last leaf for view on the conversation's list page. My message model:

class Message
 belongs_to :mailbox
 acts_as_nested_set
 ...
end

E.g. If I selected Inbox, I would want to select: roots those have any message with that belongs to Inbox. How can I do with select? Do I need to build a Conversation model that would have message_id, mailbox_id, unique_thread_number for this?

Alexander Shlenchack
  • 3,779
  • 6
  • 32
  • 46

1 Answers1

0

I'd go reversely... Select messages and then get their roots.

messages=Message.where(mailbox: "inbox").map(&:id)
roots=Message.where('id in (?)',Message.where('id in (?)',messages).map {|p| p.root.id})
leaf_ids = roots.map {|p| p.leaves.last.id if p.leaves.any?}
leaves=Message.where('id in (?)', leaf_ids)

In the above logic I don't use any filtering, this means at start I select ids for all messages in inbox... I guess you will have to add some filtering (where clause) to narrow results down.

Then, you get the roots for those messages

Then, you get the leaf_ids of those roots

Your desired viewable messages will be the leaves.

Updated Now that I see it, you can do it with one less step (if you don't need the roots themselves):

messages= Message.where(mailbox: "inbox").map(&:id)
leaf_ids= Message.where('id in (?)',Message.where('id in (?)',messages).
                  map {|p| p.root.leaves.last.id if p.root.leaves.any?})
leaves  = Message.where('id in (?)',leaf_ids)
Ruby Racer
  • 5,690
  • 1
  • 26
  • 43
  • Thank you for your reply but this approach doesn't help with conversation those begin from sent folder. – Alexander Shlenchack Dec 09 '14 at 21:58
  • @AlexanderShlinchack, sorry about that... I am under the slight impression that there is some feedback missing. You think you could provide a brief yet comprehensive example in your question? – Ruby Racer Dec 09 '14 at 22:03