Skip to content

Optional filters and allow_nil #283

Description

@tmikoss

I've ran into a specific case - I'd like to allow for one of the filter values to be nil, but also for that filter to not be ran.

My use case is running dynamically constructed filters through datagrid instances to fetch data. For example, let's assume we have UsersGrid that allows filtering by referrer_id.

Given following params, I'd like to select:

  1. {} - all users, as referrer is of no concern here;
  2. { referrer_id: nil } - only those users that are not referred by anyone;
  3. { referrer_id: 123 } - only those with specific referrer value.

Currently, datagrid can't seem to distinguish between 1 & 2, because the attribute reader would return nil in both cases.

My current workaround is to set the default to some invalid value, and then skip filter when encountering that value:

    filter :referrer_id, allow_nil: true, default: DO_NOT_FILTER do |value|
      if value == DO_NOT_FILTER
        self
      else
        where(referrer_id: value)
      end
    end

Am I missing some better way to handle this case?

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions