2

现在,我正在使用一个名为“mailboxer”的 gem 用于消息传递系统。https://github.com/ging/mailboxer
我想为收件箱、发件箱和垃圾箱实现“关键字搜索功能”。

如果我不关心搜索关键字,它会通过这样的编码毫无问题地获取结果

inbox...   @messages = current_user.mailbox.inbox.page(params[:page]).per(10)
sentbox... @messages = current_user.mailbox.sentbox.page(params[:page]).per(10)    
trash...   @messages = current_user.mailbox.trash.page(params[:page]).per(10)

但我有时想用搜索关键字过滤结果。
假设本次搜索关键字是'test',结果应该只是通知表中body属性中包含'test'的记录。
我怎样才能为上面的每一个(如收件箱、发件箱和垃圾箱)执行此操作?

我试过这个,但它根本没有用:(

@messages = current_user.mailbox.inbox.search_messages(@search).page(params[:page]).per(10)
@messages = current_user.mailbox.sentbox.search_messages(@search).page(params[:page]).per(10)
@messages = current_user.mailbox.trash.search_messages(@search).page(params[:page]).per(10)
4

1 回答 1

0

解决方案是对 Mailboxer::Receipt 和 Mailboxer::Models::Messageable 模块进行猴子补丁,以启用按框类型进行搜索:

class Mailboxer::Receipt < ActiveRecord::Base
  ...
  if Mailboxer.search_enabled
    searchable do
      text :subject, :boost => 5 do
        message.subject if message
      end
      text :body do
        message.body if message
      end
      integer :receiver_id

      # Add mailbox_type to sunspot search field
      string  :mailbox_type
      boolean :trashed
      boolean :deleted
    end
  end
end

在 Messageable 模块下,我为每种邮箱类型添加了新的 search__messages 方法:

module Mailboxer
  module Models
    module Messageable

      def search_messages(query)

        # Replaces 'search' with alias 'solr_search' since ransack search clashes with solr search method
        @search = Mailboxer::Receipt.solr_search do
          fulltext query
          with :receiver_id, self.id
        end

        @search.results.map { |r| r.conversation }.uniq
      end

      # Adds additional Mailboxer search functionality to search by box type
      def search_inbox_messages(query)
        @search = Mailboxer::Receipt.solr_search do
          fulltext query
          with :receiver_id, self.id
          with(:mailbox_type).equal_to("inbox")
        end

        @search.results.map { |r| r.conversation }.uniq
      end

      def search_sent_messages(query)
        @search = Mailboxer::Receipt.solr_search do
          fulltext query
          with :receiver_id, self.id
          with(:mailbox_type).equal_to("sentbox")
        end

        @search.results.map { |r| r.conversation }.uniq
      end

      def search_trash_messages(query)
        @search = Mailboxer::Receipt.solr_search do
          fulltext query
          with :receiver_id, self.id
          with :trashed, true
          with :deleted, false
        end

        @search.results.map { |r| r.conversation }.uniq
      end

    end
  end
end

有了这个,在您的控制器中,您可以简单地使用新定义的方法来进行框类型搜索。

current_user.search_inbox_messages(query[:keywords])
current_user.search_sentbox_messages(query[:keywords])
current_user.search_trash_messages(query[:keywords])

重要提示:确保在添加新搜索字段后重新生成 Solr 索引,否则将不会显示任何内容:

bundle exec rake sunspot:solr:reindex

希望这可以帮助!

于 2014-06-10T02:27:12.203 回答