Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Here's a solution using a self-referential relationship using single table inheritance. Use these commands to create the app:</p> <pre><code>$ rails myproject $ cd myproject $ script/generate model publication type:string name:string $ script/generate model citation publication_id:integer reference_id:integer </code></pre> <p>The setup the relationships this way:</p> <pre><code>class Publication &lt; ActiveRecord::Base has_many :citations has_many :cited_publications, :through =&gt; :citations, :source =&gt; :reference has_many :references, :foreign_key =&gt; "reference_id", :class_name =&gt; "Citation" has_many :refered_publications, :through =&gt; :references, :source =&gt; :publication end class Citation &lt; ActiveRecord::Base belongs_to :publication belongs_to :reference, :class_name =&gt; "Publication" end class Article &lt; Publication end class Book &lt; Publication end class Chapter &lt; Publication end </code></pre> <p>Now we can create the DB and try it out from the console:</p> <pre><code>$ rake db:migrate $ script/console Loading development environment (Rails 2.2.2) &gt;&gt; a = Article.create!(:name =&gt; "Article") =&gt; #&lt;Article id: 1, ...&gt; &gt;&gt; b = Book.create!(:name =&gt; "Book") =&gt; #&lt;Book id: 2, ...&gt; &gt;&gt; a.citations.create(:reference =&gt; b) =&gt; #&lt;Citation id: 1, publication_id: 1, reference_id: 2, created_at: "2009-02-15 14:13:15", updated_at: "2009-02-15 14:13:15"&gt; &gt;&gt; a.citations =&gt; [#&lt;Citation id: 1, ...&gt;] &gt;&gt; a.references =&gt; [] &gt;&gt; b.citations =&gt; [] &gt;&gt; b.references =&gt; [#&lt;Citation id: 1, publication_id: 1, reference_id: 2, created_at: "2009-02-15 14:13:15", updated_at: "2009-02-15 14:13:15"&gt;] &gt;&gt; a.cited_publications =&gt; [#&lt;Book id: 2, type: "Book", name: "Book", created_at: "2009-02-15 14:11:00", updated_at: "2009-02-15 14:11:00"&gt;] &gt;&gt; a.refered_publications =&gt; [] &gt;&gt; b.cited_publications =&gt; [] &gt;&gt; b.refered_publications =&gt; [#&lt;Article id: 1, type: "Article", name: "Article", created_at: "2009-02-15 14:10:51", updated_at: "2009-02-15 14:10:51"&gt;] </code></pre>
 

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