包含时,ActiveAdmin Helper在instance_eval上抛出错误

时间:2013-09-25 20:28:33

标签: ruby-on-rails ruby activeadmin

我有一个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。

修改

当我在'app / admin / import_helper.rb'中定义ImportHelper时,如下所示:

# 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调用应该是不必要的。

1 个答案:

答案 0 :(得分: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
}