railsadminteam / rails_admin

RailsAdmin is a Rails engine that provides an easy-to-use interface for managing your data
MIT License
7.87k stars 2.25k forks source link

Suggestion to simplify the options for customizing the title of single database record #3590

Closed dailson-igo closed 1 year ago

dailson-igo commented 1 year ago

Is your feature request related to a problem? Please describe. Make easier to customize the title of the record, especially for those who are starting with Rails Admin.

Describe proposed solution(s) I would like to suggest the following change in the Models Wiki https://github.com/railsadminteam/rails_admin/wiki/Models

Additional context By default, it tries to call the "name" or "title" methods on the record in question, as we can see in the snippet "@label_methods = %i[name title]" from the file https://github.com/railsadminteam/rails_admin/blob/master/lib/rails_admin/config.rb. If the object responds to neither, then the label will be constructed from the model's class name appended with its database identifier. You can add label methods, or override the default [:name, :title]. First, we will use the override default option by adding the configuration in the "config/initializers/rails_admin.rb" file:

config.label_methods << :description

If you have more than one field you want to use, put them in sequence

config.label_methods = %i[name title description field4]
# OR
# config.label_methods << :name << :title << :description << :field4

If the class does not have any of the fields defined for the title of the record, name and title by default, or another defined by you, we can easily configure the title of the record by creating a virtual field in the class, which must match the name of the expected field to the title of the record, for example:

class City < ApplicationRecord
   # Virtual field method
   def name
     city_name
   end

When it is not enough to solve your need to customize and change the list of fields in the file "config/initializers/rails_admin.rb", or define a virtual field, we still have the option of creating a customized method, which can be inserted in the file of Rails Admin configuration or in your class, depending on how you prefer to configure it.

Defining the object_label_method in the class, with 8 lines

object_label_method do
   :custom_label_method
end
City.class_eval do
   def custom_label_method
     city_name.to_s
   end
end

The same solution with 2 lines

object_label_method { :custom_label_method }
City.class_eval { def custom_label_method = city_name.to_s }
# For Ruby < 3.0 series
# Server.class_eval { def custom_label_method; name.to_s; end }
mshibuya commented 1 year ago

@dailson-igo Looks great, please go ahead with the change. The Wiki is editable by everyone!