Adding custom column using 'activeadmin-axlsx' gem

896 Views Asked by At

I am using activeadmin gem in my application using Rails 4. I need excel download for which I am making use of activeadmin-axlsx gem. I am able to get all the columns that exists in my database for the particular model in the excel sheet as its columns. However, what I want is, to add a column which does not exists in my database.

This is what I have tried until now

 column('start_date') do |date|
   date.start_date
 end

Here start_date is an attribute in my db and hence I get that column in the excel.

Now when I try to add another column End Date(which is not an attribute in the db), I get a blank column.

I have also tried the below snippet, referring to the Github link for activeadmin-axlsx

config.xlsx_builder.column('end_date') do |emp|
  emp.end_time.strftime("%Y-%m-%d")
end

This gives a blank column in the excel

Can anybody help me achieve this?Or suggest any other gems that can be used with activeadmin gem?

Many Thanks!

2

There are 2 best solutions below

1
On

I think you can just define one like start_date. Did you try:

column(:end_date) do |resource|
  resource.end_time.strftime('%Y-%m-%d')
end
0
On

The solution is to add the attributes that do not exist in your database as an attribute accessor in your respective model.

For the above example,

end_date is not an attribute in the table, so in the model say Employee, add this

class Employee < ActiveRecord::Base

attr_acessor :end_date

end

Here I am modifying end_time which is an attribute in database of type datetime to fetch only the date with the name of the column being End Date

In the app/admin/employee.rb

ActiveAdmin.register User do 

  xlsx do 
    column('end_date') do |emp|
      emp.end_time.strftime("%Y-%m-%d")
    end
  end
end

This would give you the desired value.