Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>There are a couple of ways you could do this. First, you could set up two <code>belongs_to</code>/<code>has_one</code> relationships:</p> <pre><code>things - bar:int - foo_id:int - goo_id:int whazits - content:string - value:int class Thing &lt; ActiveRecord::Base belongs_to :foo, :class_name =&gt; "whazit" belongs_to :goo, :class_name =&gt; "whazit" end class Whazit &lt; ActiveRecord::Base has_one :foo_owner, class_name =&gt; "thing", foreign_key =&gt; "foo_id" has_one :goo_owner, class_name =&gt; "thing", foreign_key =&gt; "goo_id" # Perhaps some before save logic to make sure that either foo_owner # or goo_owner are non-nil, but not both. end </code></pre> <p>Another option which is a little cleaner, but also more of a pain when dealing with plugins, etc., is single-table inheritance. In this case you have two classes, Foo and Goo, but they're both kept in the whazits table with a type column that distinguishes them.</p> <pre><code>things - bar:int whazits - content:string - value:int - thing_id:int - type:string class Thing &lt; ActiveRecord::Base belongs_to :foo belongs_to :goo end class Whazit &lt; ActiveRecord::Base # .. whatever methods they have in common .. end class Foo &lt; Whazit has_one :thing end class Goo &lt; Whazit has_one :thing end </code></pre> <p>In both cases you can do things like <code>@thing.foo</code> and <code>@thing.goo</code>. With the first method, you'd need to do things like:</p> <pre><code>@thing.foo = Whazit.new </code></pre> <p>whereas with the second method you can do things like:</p> <pre><code>@thing.foo = Foo.new </code></pre> <p>STI has its own set of problems, though, especially if you're using older plugins and gems. Usually it's an issue with the code calling <code>@object.class</code> when what they really want is <code>@object.base_class</code>. It's easy enough to patch when necessary.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload