Override Rails Table name

MySQL, Ruby on Rails, 2015-05-24 01:48:39 UTC

I don't know exactly what does this name in Rails. But, I named it override table name in Rails.

The case is very simple, let say We already have a table name in the database. The database name is email_dr_pengunjung. 

When We create it with rails g model command, Rails simple add s in the end of table name. So, the table name is email_dr_pengunjungs and the migration file like 20150523233040_create_email_dr_pengunjungs.rb

$ rails g model EmailDrPengunjung

 

Just open up 20150523233040_create_email_dr_pengunjungs.rb to force using 'the old table name'. And add these lines;

class CreateEmailDrPengunjungs < ActiveRecord::Migration
  def change
    self.connection.execute %Q(
      CREATE TABLE IF NOT EXISTS `email_dr_pengunjung` (
        `id` int(10) NOT NULL AUTO_INCREMENT,
        `email` varchar(255) DEFAULT NULL,
        `nama_lengkap` varchar(255) DEFAULT NULL,
        `isi` text,
        `created_at` varchar(50) DEFAULT NULL,
        PRIMARY KEY (`id`),
        KEY `id` (`id`)
      )
    )
  end
end

 

With Active Record Query, Rails use email_dr_pengunjungs as a table related to the model. But We can override the table name like below;

class EmailDrPengunjung < ActiveRecord::Base
  self.table_name = "email_dr_pengunjung"
end

Share: