title: rails polymorphic association (legacy database)
body: <p>I am using a legacy database, so i do not have any control over the datamodel. They use a lot of polymorphic link/join-tables, like this</p>
  
  <pre><code>create table person(per_ident, name, ...)
  
  create table person_links(per_ident, obj_name, obj_r_ident)
  
  create table report(rep_ident, name, ...)
  </code></pre>
  
  <p>where <code>obj_name</code> is the table-name, and <code>obj_r_ident</code> is the identifier. 
  So linked reports would be inserted as follows: </p>
  
  <pre><code>insert into person(1, ...)
  insert into report(1, ...)
  insert into report(2, ...)
  
  insert into person_links(1, 'REPORT', 1)
  insert into person_links(1, 'REPORT', 2)
  </code></pre>
  
  <p>And then person 1 would have 2 linked reports, 1 and 2.</p>
  
  <p>I can understand possible benefits having a datamodel like this, but i mostly see one big shortcoming: using constraints is not possible to ensure data integrity. But alas, i cannot change this anymore.</p>
  
  <p>But to use this in Rails, i was looking at polymorphic associations but did not find a nice way to solve this (since i cannot change the columns-names, and did not readily find a way to do that).</p>
  
  <p>I did come up with a solution though. Please provide suggestions.</p>
  
  <pre><code>class Person &lt; ActiveRecord::Base
  
    set_primary_key "per_ident"
    set_table_name "person"
    has_and_belongs_to_many :reports,
                           :join_table =&gt; "person_links",
                           :foreign_key =&gt; "per_ident",
                           :association_foreign_key =&gt; "obj_r_ident",
                           :conditions =&gt; "OBJ_NAME='REPORT'"
  end
  
  class Report &lt; ActiveRecord::Base
  
    set_primary_key "rep_ident"
    set_table_name "report"
    has_and_belongs_to_many :persons,
                       :join_table =&gt; "person_links",
                       :foreign_key =&gt; "obj_r_ident",
                       :association_foreign_key =&gt; "per_ident",
                       :conditions =&gt; "OBJ_NAME='REPORT'"
  end
  </code></pre>
  
  <p>This works, but i wonder if there would be a better solution, using polymorphic associations.</p>