Pranjal Nanavaty
Pranjal Nanavaty

Reputation: 135

rails_admin customise dropdown with belongs_to relationship

I was trying to develop a basic rails_admin application. My usecase has Projects and Students.

class Project < ApplicationRecord
    belongs_to student
end

class Student < ApplicationRecord
    has_many projects
end

As students can have the same name so, it is difficult to identify student while creating projects. I needed to combine student's roll number and name to form a unique entry in the dropdown. Thus I want the view for Project model to show list of students in the dropdown as 123 - John Doe instead of just John Doe.

Upvotes: 1

Views: 578

Answers (1)

Guillermo Siliceo Trueba
Guillermo Siliceo Trueba

Reputation: 4619

You need to define the method title

def title
  "#{roll_number} - #{full_name}"
end

As rails admin will try to display the object using first the name method and then the title method.

You can override globally this behavior like this:

RailsAdmin.config {|c| c.label_methods << :description} 

This would set the method description of any model as the one to be used to label objects.

You can also override per model like so:

RailsAdmin.config do |config|
  config.model 'Team' do
    object_label_method do
      :custom_label_method
    end
  end

  def custom_label_method
    "Team #{self.name}"
  end
end

Reference: The object_label_method method

Upvotes: 2

Related Questions