Add a reference column using migration having non standard primary key column
<p>I have a model which has a non-rails conventional primary key.</p>

<pre><code>class Guoid &lt; ActiveRecord::Base
  self.primary_key = :guoid
end
</code></pre>

<p>and related migration</p>

<pre><code>class CreateGuoids &lt; ActiveRecord::Migration
  def change
    create_table :guoids, id: false do |t|
      t.integer :guoid, limit: 8, auto_increment: true, primary_key: true
      t.integer :parent_guoid, limit: 8
      t.string :resource_type, limit: 60
    end
  end
end
</code></pre>

<p>Now I want to reference this model in another model and trying to create migration using <code>references</code> which doesn't to work.</p>

<pre><code>class ContentUnit &lt; ActiveRecord::Base
  self.primary_key = :guoid
end

class Content &lt; ActiveRecord::Base
  self.primary_key = :guoid
  belongs_to :user
  belongs_to :content_unit
end
</code></pre>

<p>and related migration</p>

<pre><code>class CreateContents &lt; ActiveRecord::Migration
  def change
    create_table :contents, id: false do |t|
      t.references :content_unit, index: true, foreign_key: true
      t.references :user, index: true, foreign_key: true
    end
  end
end
</code></pre>

<p>When I run the migration, I am getting following error.</p>

<pre><code>Mysql2::Error: Can't create table `myapp_development_cr1`.`#sql-54a_308` (errno: 150 "Foreign key constraint is incorrectly formed"): ALTER TABLE `contents` ADD CONSTRAINT `fk_rails_823443bd0d`
FOREIGN KEY (`content_unit_id`)
  REFERENCES `content_units` (`id`)
</code></pre>

<p>I am expecting to create <code>content_unit_guoid</code> foreign key in <code>contents</code> table referencing <code>guoid</code> in <code>guoids</code> table.</p>

<p>I used <a href="https://github.com/kamipo/activerecord-mysql-awesome" rel="nofollow">activerecord-mysql-awesome gem</a> to work well with non-rails convention primary keys.</p>

<p>Here is a trigger which first creates a record in <code>guids</code> table and use it's pk as pk of the target table.</p>

<pre><code>DELIMITER $$
CREATE TRIGGER `content_before_insert` BEFORE INSERT ON `content`
 FOR EACH ROW BEGIN
IF NEW.guoid = 0 THEN
    INSERT INTO `content`.guoids (resource_type)
        VALUES('Content');
    SET NEW.guoid = LAST_INSERT_ID();
END IF;
END
$$
DELIMITER ;
</code></pre>