Rails - ActiveAdmin 和 Papertrail - 一种 DRY 方法

Rails - ActiveAdmin and Papertrail - a DRY approach

我有很多使用 PaperTrail 的模型,例如:

class User < ActiveRecord::Base
  has_paper_trail
end

在我的 ActiveAdmin 模型文件中:

ActiveAdmin.register User do

  ...

  # versioning part
  action_item :history, only: :show do
    link_to('History', history_backend_user_path(user), method: :get)
  end

  sidebar :versionate, :partial => "layouts/version", :only => :show

  member_action :history do
    @user = User.find(params[:id])
    @versions = @user.versions.reorder(created_at: :desc)
    render "layouts/history"
  end
end

我必须为每个模型重复这几行,我想知道如何才能把它弄干。

尝试将公共代码分离到关注点中。然后,您可以使用 ActiveAdmin 的 include 方法将通用代码合并到您的资源中。

这是应该包含您的通用代码的模块:

# app/admin/concerns/versionable.rb
module Versionable
  def self.included(dsl)
    dsl.action_item :history, only: :show do
      link_to 'History', dsl.history_backend_user_path(user), method: :get
    end

    dsl.sidebar :versionate, :partial => "layouts/version", :only => :show

    dsl.member_action :history do
      @user = User.find(params[:id])
      @versions = @user.versions.reorder(created_at: :desc)
      render "layouts/history"
    end
  end
end

然后您可以将此模块包含在您的 ActiveAdmin 资源中。例如:

# app/admin/user.rb
ActiveAdmin.register User do
  include Versionable
  ...
end

这是基于this Stack Overflow post。尚未测试。

我最终得到了以下解决方案 ,它正在运行 (另请注意,对 User 资源的所有引用都已概括):

# app/admin-shared/active_admin_loggable.rb

module ActiveAdminLoggable
  def self.extended(base)
    base.instance_eval do
      action_item :history, only: :show do
        link_to('History',
                eval("history_backend_#{resource.class.to_s.downcase}_path(#{resource.class.to_s.downcase})"),
                method: :get
        )
      end

      sidebar :versionate, :partial => "layouts/version", :only => :show

      member_action :history do
        @this_resource = eval("resource.class").find(params[:id])
        @versions = @this_resource.versions.reorder(created_at: :desc)
        render "layouts/history"
      end
    end
  end
end

和:

# app/admin/user.rb
ActiveAdmin.register User do
  extend ActiveAdminLoggable
  ...
end