Rails_admin custom action specify template name

2019-09-02 07:13发布

问题:

My app is Rails 4.1 with rails_admin 0.8.1. I want to create custom action that only shows articles that belong to logged in user. If I were using regular Rails scaffolding I would just create a new action in articles controller and tell it to use index view.

I registered the action properly in rails_admin.rb so it shows up. But how do I specify template_name in RA? I keep getting Missing template rails_admin/main/myarticles ... when I browse to http://localhost:3000/admin/article/myarticles

class Article
  include Mongoid::Document
  field :title, type: String
  belongs_to :user
  ...
  def my_articles current_user
    Article.where(user: current_user)
  end
end

class Myarticles < RailsAdmin::Config::Actions::Base
  RailsAdmin::Config::Actions.register(self)
  register_instance_option :collection do
    true
  end
  register_instance_option :visible? do
    authorized?
  end
  register_instance_option :only do
    Article
  end
  register_instance_option :template_name do
    :index  # this does not work
  end
  register_instance_option :controller do
    proc do
      @objects = Article.my_articles(current_user)
    end
  end
end

回答1:

Finally figured it out.

  class Myarticles < Collectionaction
    RailsAdmin::Config::Actions.register(self)
    ...
    register_instance_option :controller do
      proc do
        @objects = Article.where(user: current_user)
        render :index
      end
    end
  end

You could push the filter logic into model or another object if you want to.