【问题标题】:Searchkick search on model having no or at least one associated objectSearchkick 搜索没有或至少有一个关联对象的模型
【发布时间】:2018-07-19 15:21:47
【问题描述】:

在 Rails 中,我使用的是searchkick gem。有两个模型 user 和 book,我在 user 模型上应用了 searchkick。两种模型如下:

class User < ApplicationRecord
  searchkick

  has_many :books
end

class Book < ApplicationRecord
  belongs_to :user
end

图书模型有一个类型字段。现在,我想对用户模型进行不同类型的查询。

  • 搜索未关联图书的用户。
  • 搜索至少关联一本书的用户。
  • 搜索至少拥有特定类型书籍的用户,例如“艺术”。

我尝试了许多查询,也尝试了 join,但没有用。如果有人可以帮助查询以搜索此类结果。

我不想在图书模型和用户模型中搜索,只在用户模型中搜索但有关联的图书。

【问题讨论】:

    标签: ruby-on-rails elasticsearch searchkick


    【解决方案1】:

    使用自定义search_data 方法为您的搜索索引添加图书信息。

    class User
      searchkick
    
      scope :search_import, -> { includes(:books) }
    
      def search_data
        {
          books_count: books.count,
          book_types: books.map(&:book_type)
        }
      end
    end
    
    class Book
      after_commit :reindex_user
    
      def reindex_user
        user.reindex # or reindex_async
      end
    end
    

    然后搜索:

    User.search("*", where: {books_count: 0})
    User.search("*", where: {books_count: {gt: 0}})
    User.search("*", where: {book_types: "Art"}) 
    

    【讨论】:

      猜你喜欢
      • 2017-06-14
      • 1970-01-01
      • 2022-01-13
      • 2019-05-21
      • 2014-02-11
      • 1970-01-01
      • 1970-01-01
      • 2018-08-28
      相关资源
      最近更新 更多