4

我有一个 ActiveAdmin 的辅助方法,它定义了一些在所有模型中都相同的操作。

在'app/helpers/active_admin/import_helper.rb'

module ActiveAdmin
  module ImportHelper

    def self.included(base)
      base.instance_eval do
        action_item only: :index do
          link_to "Import", action: :import
        end

        collection_action :import do
          render "admin/import"
        end

        controller do

          def save_csvimport(item)
            # .. import stuff

            redirect_to action: :index
          end

          def permitted_params
            params.permit!
          end
        end
      end
    end

  end
end

在'app/admin/categories.rb'

ActiveAdmin.register Store::Category do
  include ImportHelper

  config.filters = false

  collection_action :importcsv, method: :post do
    save_csvimport "Category"
  end
end

在应用程序启动时,我收到以下错误:

app/helpers/active_admin/import_helper.rb:6:in `block in included': undefined method `action_item' for #<Module:0x007f93efabac40> (NoMethodError)

如何在所有 'admin/*.rb' 文件中定义这些方法?(此导入功能在所有模型中都是相同的。)

我正在使用 ruby​​ 2.0 和 rails 4。

编辑:

当我ImportHelper像这样在 'app/admin/import_helper.rb' 中定义时:

# Note no namespacing
module ImportHelper

  def self.included(base)
    base.instance_eval do
      action_item only: :index do
        link_to "Import", action: :import
      end

      collection_action :import do
        render "admin/import"
      end

      controller do

        def save_csvimport(item)
          # .. Import stuff

          redirect_to action: :index
        end

        def permitted_params
          params.permit!
        end
      end
    end
  end
end

'categories.rb' 像这样:

ActiveAdmin.register Store::Category do

  config.filters = false

  require_relative "./import_helper"
  include ImportHelper

  collection_action :importcsv, method: :post do
    save_csvimport "Category"
  end
end

一切正常。但是,这对我来说似乎很乱,因为导入文件不应该在“app/admin”中,而且require_relative调用应该是不必要的。

4

1 回答 1

0

另一种方法:

# This one needs to be loaded before every ActiveAdmin resource that is using it. I usually place it at:
# app/admin/_defaults.rb
module ActiveAdmin::Defaults
  def self.default_config(&block)
    proc{
      breadcrumb do
        # ...
      end

      menu false

      before_filter :except => [:show] {
        # ...
      }

      controller do
        # ...
      end
      instance_exec(&block) if block_given?
    }
  end
end

# app/admin/users.rb
ActiveAdmin.register User, &ActiveAdmin::Defaults.default_config{
  index do
    # ...
  end

  show do
    # ...
  end
}
于 2013-09-26T20:35:10.773 回答