You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Rails Admin中筛选polymorphic association的活跃关联对象

Rails Admin 多态关联下拉仅显示激活状态数据方案

针对你遇到的多态关联下拉筛选问题,提供两种可行的配置方案:

方案一:给关联模型设置默认激活Scope

通过给Employee和Product配置Rails Admin的默认Scope,让关联下拉自动继承激活数据的查询条件:

# config/initializers/rails_admin.rb
RailsAdmin.config do |config|
  config.model 'Employee' do
    # 配置默认Scope为仅激活状态
    scope :active, default: true, show_count: true do
      where(is_active: true)
    end
    list do
      scopes [:active]
    end
  end

  config.model 'Product' do
    scope :active, default: true, show_count: true do
      where(is_active: true)
    end
    list do
      scopes [:active]
    end
  end
end

该方案会全局生效,所有涉及这两个模型的Rails Admin关联下拉都会只显示激活记录。

方案二:在Picture模型中自定义关联下拉查询

仅针对Picture的imageable关联下拉做筛选,不影响其他场景的模型查询:

# config/initializers/rails_admin.rb
RailsAdmin.config do |config|
  config.model 'Picture' do
    edit do
      field :imageable do
        associated_collection_scope do
          scope = Proc.new { |scope|
            # 仅对Employee和Product模型应用激活筛选
            if %w[Employee Product].include?(scope.model.name)
              scope.where(is_active: true)
            else
              scope
            end
          }
          { scope: scope }
        end
      end
    end
  end
end

注意事项

  • 配置修改后需重启Rails服务器生效
  • 若之前有自定义Scope,需检查是否存在逻辑冲突
  • 两种方案可根据业务需求选择,方案一更通用,方案二更精准

内容的提问来源于stack exchange,提问作者Manjula Mv

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.31 01:57:37