首页 > 解决方案 > Rails 4 / Filterrific gem - 布尔字段问题

问题描述

在我的应用程序中,我有一个称为字段testedboolean字段。

我想要实现的是一个简单的checkbox用户可以根据tested.

在我的模型中,我有:

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

在我看来/形式我有:

= f.check_box :with_tested

在我的模型中,我也尝试了不同的方法,但没有成功:

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])
}

当我尝试基于 过滤时tested,我可以看到我的过滤器正在尝试过滤(我看到过滤器旋转),但我的记录没有被正确过滤。

我不确定我做错了什么。任何建议和帮助表示赞赏!

过滤器的所有其他部分工作正常

PS:我没有with_tested在我的控制器中添加,因为我知道我不需要它


版本:

Ruby on Rails:4.2.4

过滤:2.1.2

标签: ruby-on-rails-4checkboxfilterrific

解决方案


问题是where(tested: [flag]),因为它尚未设置truefalse。要解决这个问题where,应该知道value这种情况下是什么。

所以where(tested: [flag])应该改为:where(tested: true)where(tested: false)

首先,您需要在您的model:

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

在您view执行以下操作:

= f.check_box :with_tested

:with_tested在您的控制器中添加available_filters.

PS:代码已经过测试并且可以工作


推荐阅读