How to change how ActiveAdmin displays time (each time)

Since the default time in the database is in utc, I would like to be able to display it at the right time for users. To do this, I had to take column :created_at and change it to this:

 index do ... column :created_at, :sortable => :created_at do |obj| obj.created_at.localtime.strftime("%B %d, %Y %H:%M) end ... end 

It seems pretty easy to do it once or twice, but when you need to override each indexing and display method, the process will get a little tax.

Is there a way to override how ActiveAdmin displays time without having to override each event?

I know that I can create a function, or perhaps it’s better to use functions that provide time, but I still have to use it every time I want to display the time. I want to redefine it without worrying that I missed it.

+8
datetime ruby-on-rails activeadmin
source share
3 answers

I found two ways to do this:

1. Javascript

This is a simpler method because it is very short and does not include adding a db field. It works because it uses the time zone of users from its browser. This answer gives an idea of ​​how to do this.

2. From the database

This process can be found in this railscast .

Essentially store the time_zone field in the users table. Then use the before_filter parameter (although it may be better than round_filter) to set the time zone in the controller.

 before_filter :set_time_zone private def set_time_zone Time.zone = current_user.time_zone if current_user end 
+4
source share

You can only target ActiveAdmin by specifying that it always uses a specific filter in config/initializers/active_admin.rb by adding a line similar to this:

 config.before_action :set_admin_timezone 

(or config.before_filter :set_admin_timezone for Rails versions before Rails 4)

Then in your ApplicationController, you can simply define the set_admin_timezone method, and ActiveAdmin will use it. For example:

 def set_admin_timezone Time.zone = 'Eastern Time (US & Canada)' end 

You should find the current user in this method (to get a specific time zone), but I have not tried this.

+15
source share

So, for my understanding you need two things:

  • Localtime / timezone

    You can achieve this by setting the correct time zone for your rails application, active_admin will get this by default. For example, in the rails configuration file (config / application.rb):

    config.time_zone = 'Eastern Time (US and Canada)'

  • Default time format

    You can reference this Change default date format in active admin

Good luck ~

+2
source share

All Articles