Search code examples
ruby-on-rails-4checkboxfilterrific

Rails 4 / Filterrific gem - Problem with boolean field


In my application, I have a field called tested which is a boolean field.

What I want to achieve is a simple checkbox where users can check or uncheck & filter based on tested.

In My model I have:

filterrific :default_filter_params => { :sorted_by => 'created_at_desc' },
              :available_filters => %w[
                sorted_by
                search_query
                with_created_at_gte
                with_tested
              ]
scope :with_tested, lambda { |flag|
    return nil  if 0 == flag # checkbox unchecked
    where(tested: true)
}

/// Other scopes

and In my view/form I have:

= f.check_box :with_tested

In my model I have also tried different approaches with no luck:

scope :with_tested, lambda { |value|
  where('posts.tested = ?', value)
}

// and 

scope :with_tested, lambda { |query|
  return nil  if 0 == query # checkbox unchecked
  where('posts.tested == ?', query)
}

// and

scope :with_tested, lambda { |flag|
    return nil  if 0 == flag # checkbox unchecked
    where(tested: [flag])
}

When I try to filter based on tested, I can see that my filter is trying to filter (I see the filter spin), but my records are not filtered correctly.

I'm not sure what I have done wrong. Any suggestion and help is appreciated!

All other parts of the filter work fine

PS: I haven't added with_tested in my controller as I got to know I don't need it


Versions:

Ruby on Rails: 4.2.4

Filterrific: 2.1.2


Solution

  • The problem is where(tested: [flag]), because it hasn't been set to true or false. To fix the issue where should know what the value is in that case.

    So where(tested: [flag]) should be changed to: where(tested: true) or where(tested: false).

    First, you need to specify this in your model:

    scope :with_tested, lambda { |flag|
          return nil  if 0 == flag # checkbox unchecked
          where(tested: true)
        }
    

    In your view do the following:

    = f.check_box :with_tested
    

    and add :with_tested in your controller in available_filters.

    PS: Code has been tested and works