Tag Archives: Active admin

Add custom style for active admin boolean fileds

Sometimes you need to add custom styles in your active admin as per project requirement.

You can do that just adding few method in your initializer file active_admin.rb

Code:

# It extends activeadmin to show pretty boolean values
# 
# config/initializers/active_admin.rb

 module ActiveAdmin
  module Views
    class TableFor
      def bool_column(attribute)
        column(attribute) { |model| model[attribute] ? '✔'.html_safe : '✗'.html_safe }
      end

      def seller_column(attribute)
        column(attribute) { |model| model[attribute] ? 'Yes' : 'No' }
      end
    end

    class AttributesTable
      def bool_row(attribute)
        row(attribute) { |model| model[attribute] ? '✔'.html_safe : '✗'.html_safe }
      end

      def seller_row(attribute)
        row(attribute) { |model| model[attribute] ? 'Yes' : 'No' }
      end
    end
  end
end

Use in active admin:

# example
# app/admin/user.rb
 
ActiveAdmin.register User do
  index do
    column :name
    column :email
    bool_column :admin
    seller_column :seller
  end
  show do
    attributes_table do
      row :name
      row :email
      bool_row :admin
      seller_row :seller
    end
  end
end

That’s it. Happy coding 🙂

Has And Belongs To Many (HABTM) relation in active admin

Few days ago I faced a problem showing relation of Has And Belongs To Many (HABTM) in active admin.

Here is a solution I find it.

I have two model:
Company:

class Company < ActiveRecord::Base

  belongs_to              :industry
  has_and_belongs_to_many :job_titles

  attr_accessible :contact_number, :contact_person, :email, :industry_id, :name, :website, :job_titles
  accepts_nested_attributes_for :job_titles, :allow_destroy => false
  attr_accessible :job_titles_attributes
end

And Job Title:

class JobTitle < ActiveRecord::Base

  has_and_belongs_to_many :interns
  has_and_belongs_to_many :companies

  attr_accessible :name
end

Companies.rb:

ActiveAdmin.register Company do
  index do
    column :name
    column :website
    column "Jobs" do |company|
      (company.job_titles.map{ |p| p.name }).join(', ').html_safe
    end
    column :contact_person
    column :contact_number
    column :email
    column :created_at
    column :updated_at
    default_actions
  end


  show do |ad|
    attributes_table do
      row :name
      row :website
      row "Jobs" do |company|
        (company.job_titles.map{ |p| p.name }).join(', ').html_safe
      end
      row :contact_person
      row :contact_number
      row :email
      row :created_at
      row :updated_at
    end
  end

end

That’s it.