Monthly Archives: June 2013

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.

Error: Ruby on Rails 3.2 Can’t connect to local MySQL server through socket

I got an error when running rake db:migrate to create database is:

Can’t connect to local MySQL server through socket ‘/tmp/mysql.sock’ (2)

This is problem for wrong socket in databse.yml file

To solve this error first find your socket file

mysqladmin variables | grep socket

For me, this gives:

| socket              | /var/run/mysqld/mysqld.sock           

Then, add a line to your config/database.yml:

development:
  adapter: mysql2
  host: localhost
  username: root
  password: xxxx
  database: xxxx
  socket: /var/run/mysqld/mysqld.sock

This will solve this problem.