ruby-on-railsrubyrubygemsadministraterails-administrate

Administrate gem - how to show attribute which target model does not have as column, on index page


I'm trying to show attributes which a model does not have as column.

For example, I want to show "total_salary" on user index dashboard. User model's schema is as followings,

id int
name string
age int

As above, User model does not have column "total_salary".

I changed dashboard page which was generated automatically by administrate gem.

Before

ATTRIBUTE_TYPES = {
 id: Field::Number
 name: Field::String
 age: Field::Number
}

COLLECTION_ATTRIBUTES = {
 id: Field::Number
 name: Field::String
 age: Field::Number
}

After

ATTRIBUTE_TYPES = {
 id: Field::Number
 name: Field::String
 age: Field::Number
 total_salary: Field::Number # Changed 
}

COLLECTION_ATTRIBUTES = {
 id: Field::Number
 name: Field::String
 age: Field::Number
 total_salary: Field::Number # Changed 
}

Where to add logic to calculate each user's total salary? (If file witch already exists, please teach me the file path. If I have to create new file or folder, please teach me where to make.)

Thanks,


Solution

  • Looks like you need a custom field since total_salary doesn't map to a column. To do this you need to add a class to calculate it:

    # app/fields/total_salary_field.rb
    
    class TotalSalaryField < Administrate::Field::Base
      def total_salary
        # Perform calculation here
      end
    end
    

    and then do:

    ATTRIBUTE_TYPES = {
      ...,
      total_salary: TotalSalaryField,
      ...
    }
    

    Here's a link to the documentation for custom field types: https://administrate-demo-prerelease.herokuapp.com/adding_custom_field_types