简体   繁体   中英

Rails ActiveAdmin modify resource object

I've currently got a user object but to avoid redundancy, I'd like to wrap it into a presenter object called MerchantUser/ProviderUser. However, with ActiveAdmin, I'm a little confused on how to do this. I've tried using before_create to change the user into the corresponding presenters but in index...do, I'm still seeing that user.class is equal to User and not the wrapper classes that I've defined.

I've looked into scoping_collection but unfortunately that only works on collections and not individual objects?

 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

Have you looked into Active Admin's support for decorators? This page is quite comprehensive. The best way to implement them depends on how your decorator/presenter object is implemented.

Link summary: use decorate_with or look into using this gem for PORO support

Are you sure you want/need a presenter here? You can register the same Rails model multiple times as ActiveAdmin resources with different names and customizations (filters, index page, forms, etc). You can also use Rails STI or just subclass Rails models, perhaps with different Rails default_scope and then register the subclasses.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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