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.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s