Skip to content

Index search is scoped to models default_scope  #975

@aliaksandrb

Description

@aliaksandrb

Hi, thanks for the gem!

Let's say we have records that could be soft deleted (or any other default grouping property), and we want to search all records, but hide deleted by default:

class User < ApplicationRecord
  default_scope -> { where(deleted: false) }
end
class UserIndex < Chewy::Index
  index_scope User.unscoped

  field :deleted, type: "boolean"
end

With such setup, search by deleted: false works as expected ✅

Though, search by deleted: true doesn't work, because ActiveRecord adapter most of the time uses target.connection for queries, where target determined from relation.klass, here:

if class_or_relation.is_a?(relation_class)

So, while response from Elastic has hits for such query (deleted: true), afterwards Chewy queries model directly with ids being found, which guarantee to return empty dataset every time (because of contradiction: we search for deleted, while querying only not deleted), ex:

User.where(id: ids_found_for_deleted_records_from_elastic_hits) # <= but User is scoped!

This looks like a bug for me, as we probably should query the same scope as we provide to index_scope method (everything what is indexed supposed to be searchable).

A little workaround is possible by extracting search results ids re-query them manually, like, but I would assume it should be a default behavior.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions