如何在Active Admin中为Order模型添加关联Organization的过滤器或基于现有过滤器创建自定义过滤器
给Order的Active Admin页面添加Organization筛选器
要实现在Order的Active Admin页面按Organization筛选的需求,我们可以基于现有的模型关联来配置过滤器,同时先确保模型关联的正确性(因为你的模型使用自定义主键Ref,需要显式配置)。
第一步:修正模型关联(关键前提)
由于你的模型使用Ref作为主键而非默认的id,需要显式指定主键和外键,否则关联查询会出错:
class Order < ApplicationRecord self.primary_key = 'Ref' # 指定Order的主键是Ref belongs_to :store, foreign_key: 'Store', primary_key: 'Ref' # Order的Store字段对应Store的Ref end class Store < ActiveRecord::Base self.primary_key = 'Ref' # 指定Store的主键是Ref belongs_to :organization, foreign_key: 'OrganizationRef', primary_key: 'Ref', required: false # Store的OrganizationRef对应Organization的Ref end class Organization < ActiveRecord::Base self.primary_key = 'Ref' # 指定Organization的主键是Ref has_many :stores, foreign_key: 'OrganizationRef', primary_key: 'Ref', autosave: true # 关联Store的OrganizationRef字段 end
第二步:配置Order的Active Admin过滤器
接下来修改Order的Active Admin配置,新增按Organization筛选的过滤器:
ActiveAdmin.register Order do # 保留原有的Store筛选器(如果不需要可以删除) filter :store, collection: Store.includes(:organization).references(:organization).collect { |store| [store.organization&.Name, store.Ref] }, as: :searchable_select, multiple: true # 新增的Organization筛选器 filter :store_organization, as: :searchable_select, multiple: true, label: 'Організація', # 和Store页面的标签保持一致 collection: proc { Organization.all.map { |org| [org.Name, org.Ref] } }, # 显示Organization名称,值为Ref method: :store_organization_ref_in # 自定义筛选方法,匹配关联的Ref # 预加载关联数据,避免N+1查询,提升性能 controller do def scoped_collection super.includes(store: :organization) end end end
代码解释
store_organization过滤器:利用Rails的嵌套关联(Order → Store → Organization),ActiveAdmin可以识别store_organization这个关联路径。method: :store_organization_ref_in:告诉ActiveAdmin使用自定义的查询条件,匹配Store的OrganizationRef等于选中的Organization的Ref,自动生成正确的SQL WHERE子句。includes(store: :organization):提前预加载关联的Store和Organization数据,避免在筛选或列表加载时产生大量的单独查询,优化性能。proc集合:使用延迟加载的proc来获取Organization选项,确保每次打开页面时都是最新的组织数据。
这样配置后,你就能在Order的Active Admin页面看到一个名为"Організація"的搜索选择器,选择对应的组织后,就能筛选出属于该组织下所有门店的订单了。
内容的提问来源于stack exchange,提问作者Максим Брегін
相关产品推荐
相关产品推荐

