简体   繁体   English

在 ActiveAdmin 过滤器中使用 ActiveRecord 范围——仅在选中时应用过滤器

[英]Use ActiveRecord scope in ActiveAdmin filter -- only apply the filter if checked

I have an ActiveRecord class Foo and I have an ActiveAdmin index view listing all my foos.我有一个ActiveRecordFoo ,我有一个 ActiveAdmin 索引视图,列出了我所有的 foo。 Foo has a scope called bland and my UI requirement is that I have a checkbox in the Filters section so that I can see all the bland foos. Foo有一个名为bland的范围,我的 UI 要求是我在过滤器部分有一个复选框,以便我可以看到所有平淡的 foos。

Ie, I'd like the Filters section to look like this:即,我希望过滤器部分看起来像这样:

在此处输入图片说明

I have read through questions and blogs like the following that say I need a custom ransacker:我已经阅读了如下问题和博客,这些问题和博客说我需要一个自定义的掠夺者:

Use ActiveRecord scope in ActiveAdmin filter 在 ActiveAdmin 过滤器中使用 ActiveRecord 范围

So my code is something like this:所以我的代码是这样的:

ActiveAdmin.register Foo
  filter :bland, label: 'Bland Foos', as: :check_boxes, collection: ['exclude tasty']
end

class Foo < ApplicationRecord
  scope :bland, -> { where("tasty < 3") }
  def self.ransackable_scopes(_auth_object = nil)
    [:bland]
  end
end

However, when I try to run this I get an error like:但是,当我尝试运行它时,出现如下错误:

undefined method `bland_in' for #Ransack::Search:0x00007f8d18e61db8 #Ransack::Search:0x00007f8d18e61db8 的未定义方法`bland_in'

Ouch.哎哟。

As an experiment I tried something like this:作为一个实验,我尝试了这样的事情:

ActiveAdmin.register Foo
  filter :bland, label: 'Bland Foos'
end

class Foo < ApplicationRecord
  scope :bland, -> (dummy_param_not_used) { where("tasty < 3") }
  def self.ransackable_scopes(_auth_object = nil)
    [:bland]
  end
end

My idea here being: ok, ActiveAdmin will put up a string input and we'll fill in a value just to trigger the code ... but then the filter doesn't even show on my UI!我的想法是:好的,ActiveAdmin 将提供一个字符串输入,我们将填写一个值来触发代码......但是过滤器甚至不会显示在我的 UI 上!

See if this can be of any use.看看这是否有任何用处。 You can change UI elements if required.如果需要,您可以更改 UI 元素。

ActiveAdmin.register Foo
  ......
  scope :bland, -> { where("tasty < 3") }
  ......
end

Reference : ActiveAdmin Documentation参考: ActiveAdmin 文档

One way to easily resolve that issue is adding suffix轻松解决该问题的一种方法是添加后缀

_in _在

ActiveAdmin.register Foo
  filter :bland, label: 'Bland Foos'
end

class Foo < ApplicationRecord
  scope :bland_in, -> (dummy_param_not_used) { where("tasty < 3") }
  def self.ransackable_scopes(_auth_object = nil)
    [:bland_in]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM