-1

Now I'm using a gem called 'mailboxer' for messaging system.https://github.com/ging/mailboxer I'd like to implement 'keyword search function' , with that I should be able to search conversations and messages of my mailbox, either it should be from inbox, sentbox, trash or drafts.

however this gem has given a function

search_messages(query)

, but it seems not working.

Anand
  • 6,457
  • 3
  • 12
  • 26
  • What do you mean when you say that it is not working? What's the error? How did you try to use it? What is your exact problem, here? – vijoc Aug 17 '17 at 09:38
  • hi @vijoc actually when i use that function like i got error that undefined method 'search', ex - current_user.search_messages('test mail'), here 'test mail' i m passing as query for that function. – Anand Aug 17 '17 at 11:20

1 Answers1

0

Here's a function to retrieve all conversations which subject, body or recipient/sender's username includes a given string. You can tweak it little bit to fit your scenario or open an issue on their github repo.

def conversations_for(query)
  wildcarded_query = "%#{query}%"
  user_ids = User.where('CONCAT(first_name, " ", last_name) LIKE :query', query: wildcarded_query).pluck(:id)
  current_user.mailbox.conversations.
                       joins(:messages).
                       references('mailboxer_conversations, mailboxer_notifications, mailboxer_receipts, messages_mailboxer_conversations, mr, mn'). # To get rid of warnings
                       select('mailboxer_conversations.*, mailbox_type, trashed').
                       where("mailboxer_notifications.subject LIKE :query
                              OR mailboxer_notifications.body LIKE :query
                              OR mailboxer_notifications.sender_id IN (:user_ids)
                              OR EXISTS ( SELECT * FROM mailboxer_receipts mr
                                                   INNER JOIN mailboxer_notifications mn ON mn.id = mr.notification_id
                                                   WHERE mn.conversation_id = mailboxer_conversations.id
                                                   AND mr.notification_id IN ( SELECT id FROM mailboxer_notifications
                                                                                           WHERE sender_id = :current_user_id )
                                                   AND mr.receiver_id IN (:user_ids))",
                              query: wildcarded_query, user_ids: user_ids, current_user_id: current_user.id)
end
Roshan
  • 905
  • 9
  • 21