Auto reloading Rails Admin
How to avoid restarting your server when making Rails Admin changes
Shifting from Rails 6 to Rails 7 has made us have to make some changes to how we structure some of our Rails apps. One of these changes was where we located our Rails Admin configuration.
Previously we had located our Rails Admin config in their own files within app/models/concerns/
and required them within each referenced model. Changes to how Rails loaded in Rails Admin made us change to having our config situated entirely within config/initializers/rails_admin.rb
this meant we could set up auto reloading. You can only use auto reloading if all of your config sits in rails_admin.rb
.
The below code is borrowed heavily from the Rails Admin documentation. I have written this article as I was slightly confused by the documentation.
First off you’ll want to add this to your Rails Admin config file:
rails_admin.rb
RailsAdmin.config do |config|
config.parent_controller = ApplicationController.to_s
# other code...
end
Then in your application controller you’ll want to add this:
application_controller.rb
class ApplicationController < ActionController::Base
protect_from_forgery
before_action :reload_rails_admin, if: :rails_admin_path?
# Your other application controller code...
private
def reload_rails_admin
# List all the models you want to auto reload
models = %W(User
Article
Comment
OtherModel
AnotherModel)
models.each do |m|
RailsAdmin::Config.reset_model(m)
end
RailsAdmin::Config::Actions.reset
load(Rails.root.join('config/initializers/rails_admin.rb'))
end
def rails_admin_path?
controller_path =~ /rails_admin/ && Rails.env.development?
end
end
This has been great as it’s meant we haven’t had to constantly restart the server when making small changes to the admin, which can be pretty frustrating when you’re trying to maintain focus.