title: How to specify polymorphic association with custom primary keys in Rails
body: <p>I have a few ActiveRecord classes using <a href="https://github.com/airblade/paper_trail/" rel="nofollow">paper_trail</a> for version tracking. The AR classes have custom primary keys based on their table names (e.g. <code>Item.ItemID</code> instead of <code>Item.id</code>) in order to adhere to business DB conventions.</p>
  
  <p>paper_trail specifies a polymorphic relationship on each of the tracked classes, thus:</p>
  
  <pre><code>class TrackedExample &lt; ActiveRecord::Base
      set_table_name 'TrackedExample'
      set_primary_key 'TrackedExampleID'
  
      # simplified from https://github.com/airblade/paper_trail/blob/master/lib/paper_trail/has_paper_trail.rb
      has_many :versions
          :class_name =&gt; 'Version'
          :as         =&gt; :item,
  end
  
  class AnotherTrackedExample
      set_table_name 'AnotherTrackedExample'
      set_primary_key 'AnotherTrackedExampleID'
  
      has_many :versions
          :class_name =&gt; 'Version'
          :as         =&gt; :item,
  end
  
  # from https://github.com/airblade/paper_trail/blob/master/lib/paper_trail/version.rb
  class Version
      belongs_to :item, :polymorphic =&gt; true
      ...
   end
  </code></pre>
  
  <p>If I were not using custom primary keys, the version object could refer to the tracked object (i.e. the object of which it is a version) using <code>Version#item</code>. When I try it, I get an error:</p>
  
  <pre><code># This should give back `my_tracked_example`
  my_tracked_example.version.first.item
  
  =&gt; TinyTds::Error: Invalid column name 'id'.: EXEC sp_executesql N'SELECT TOP (1) [TrackedExample].* FROM [TrackedExample] WHERE [TrackedExample].[id] = 1 ORDER BY TrackedExample.TrackedExampleID ASC'
  </code></pre>
  
  <p>Is there a way to get Version#item to perform the correct query? I would expect something like this:</p>
  
  <pre><code>EXEC sp_executesql N'SELECT TOP (1) [TrackedExample].* FROM [TrackedExample] WHERE [TrackedExample].[TrackedExampleID] = 1 ORDER BY TrackedExample.TrackedExampleID ASC'
  </code></pre>
  
  <p>I'm using Rails 3.1.0, paper_trail 2.6.4 and MS SQL Server through TinyTDS and <a href="https://github.com/rails-sqlserver/activerecord-sqlserver-adapter" rel="nofollow">activerecord-sqlserver-adapter</a>.</p>
  
  <p><strong>EDIT:</strong> I've worked around the problem by adding computed columns <code>TrackedExample.id</code> and <code>AnotherTrackedExample.id</code> that refer to the primary key values. This isn't a proper solution (Rails is still making the wrong query), but it may be useful to others in a hurry.</p>
  
  <p>MS SQL:</p>
  
  <pre><code>ALTER TABLE TrackedExample
      ADD COLUMN id AS TrackedExampleID
  </code></pre>