ActiveAdmin 过滤器:一个 has_many: 通过属性

ActiveAdmin filter: a has_many: through attribute

我想在通过 has_many :foo through: :bar 关系链接的模型属性上过滤 ActiveAdmin table。

例如,如果一本书

has_many :borrowers, through: :book_checkouts

...如何在图书的 ActiveAdmin 页面上添加过滤器选项,让用户在 borrower_id 上进行过滤? (作为一个字符串;我们的图书馆有很多借阅者,所以在这里使用 Select 很笨拙。)

背景

在您的 ActiveAdmin 页面中,您可以像这样添加过滤器:

filter :column_name_1
filter :column_name_2

所以您将为 borrowers 创建一个新的过滤语句,但默认情况下,它将创建一个 select。

filter :borrowers

解决方案

因此,为了告诉它您不想使用 select,您必须使用您要过滤的关联中的列来修改您给它的符号。因此,如果您想按借款人的 ID 进行过滤,您可以这样做:

# You specify as: :numeric to so ActiveAdmin knows to add 
# filtering options for numbers. So when it renders on the page,
# for the filter option it will display three options to filter by:
# ID equals, is greater than, or is less than

filter :borrowers_id, as: :numeric

如果您想按另一个字符串列进行过滤,例如 name,您将执行以下操作:

filter :borrowers_name, as: :string

注意:我还注意到如果您没有指定 as: :type 那么 ActiveAdmin 将无法识别过滤器并且不会为它呈现任何内容。

得到问题回答的帮助: