Rails ActiveAdmin 修改资源对象

Rails ActiveAdmin modify resource object

我目前有一个用户对象,但为了避免冗余,我想将它包装到一个名为 MerchantUser/ProviderUser 的演示者对象中。但是,对于 ActiveAdmin,我对如何执行此操作感到有些困惑。我试过使用 before_create 将用户更改为相应的演示者,但在索引中...做,我仍然看到 user.class 等于用户而不是包装器 类我定义的。

我已经研究过 scoping_collection,但不幸的是,它只适用于集合而不适用于单个对象?

 ActiveAdmin.register User, as: "Companies" do # rubocop:disable Metrics/BlockLength
  before_create do |user|
    if user.merchant?
      user = MerchantUser.new(user)
    else
      user = ProviderUser.new(user)
    end
  end

  actions :all, except: [:destroy]
  permit_params :name, :email, contract_attributes: [:id, :flat_rate, :percentage]

  filter :role, as: :select
  index do # rubocop:disable Metrics/BlockLength
    column :name do |user|
      user.name <---I want it so I can just do this without the if/else blocks like below.
    end
    column :role
    column :contact_phone
    column :email
    column :website do |user|
      if user.merchant?
        user.company.website
      else
        user.provider.website
      end
    end

    column :flat_rate do |user|
      money_without_cents_and_with_symbol(user.contract.flat_rate)
    end
    column :percentage do |user|
      number_to_percentage(user.contract.percentage, precision: 0)
    end
    actions
  end

您是否研究过 Active Admin 对装饰器的支持? This page 比较全面。实施它们的最佳方式取决于您的 decorator/presenter 对象的实施方式。

Link 总结:使用 decorate_with 或考虑使用 this gem 支持 PORO

您确定您 want/need 是这里的主持人吗?您可以将相同的 Rails 模型多次注册为具有不同名称和自定义(过滤器、索引页面、表单等)的 ActiveAdmin 资源。您还可以使用 Rails STI 或仅子类 Rails 模型,也许使用不同的 Rails default_scope 然后注册子类。