Search code examples
ruby-on-rails-3.1activeadminmodel-associations

How to use Rails Gem Active Admin with basic associations


I'm new to Rails and I want to use Active Admin on my first project to manage 2 nested objects but I'm stumbling on the filters (non-friendly labels).

Here are my 2 models :

class Utilisateur < ActiveRecord::Base

  has_many :etablissements, :dependent => :destroy  
  attr_accessible :email, :nom  

end

class Etablissement < ActiveRecord::Base

  belongs_to :utilisateur  
  attr_accessible :intitule

end

Then in app/admin/etablissements.rb I have :

ActiveAdmin.register Etablissement do

  filter :intitule
  filter :utilisateur, :as => :select, :collection => proc { Utilisateur.all }

end

But the select field looks like :

<label for="q_utilisateur_id_eq">Utilisateur</label>
<select id="q_utilisateur_id_eq" name="q[utilisateur_id_eq]">
<option value="">Any</option>
<option value="1">#&lt;Utilisateur:0x00000129dbfd60&gt;</option>
<option value="2">#&lt;Utilisateur:0x00000129dbf9c8&gt;</option>
</select>

Those option-labels are clearly not user-friendly. Any ideas on how to have the :email field or any other custom field as the option-label ?

Thanks for your help


Solution

  • Create a display_name method in your model:

    class Utilisateur < ActiveRecord::Base
    
      has_many :etablissements, :dependent => :destroy  
      attr_accessible :email, :nom  
    
      def display_name
        "#{nom}, #{email}"
      end
    
    end
    

    You can read more in the source of the gem itself, i assume you know where to find it on your system. See for example:

    path-to-active-admin-gem/lib/active_admin/application.rb
    

    In that file you will see this method:

    # Active Admin makes educated guesses when displaying objects, this is
    # the list of methods it tries calling in order
    setting :display_name_methods, [ :display_name,
                                      :full_name,
                                      :name,
                                      :username,
                                      :login,
                                      :title,
                                      :email,
                                      :to_s ]
    

    Good luck et bonne chance!