Note that there are some explanatory texts on larger screens.

plurals
  1. PORuby on Rails: belongs_to and has_many over the same pair on the same model
    text
    copied!<p>First, my model definitions:</p> <pre><code>class Certificate &lt; ActiveRecord::Base belongs_to :certificate_series end class CertificateSeries &lt; ActiveRecord::Base has_many :certificates belongs_to :last_certificate_in_series, :class_name =&gt; "Certificate", :foreign_key =&gt; :last_certificate_in_series_id end </code></pre> <p>I thought of the association as: CertificateSeries have many Certificates and have a Certificate which is the last one in the series. I've thought of using have_one, but according to the <a href="http://guides.rubyonrails.org/association_basics.html#the-has_one-association" rel="nofollow">association basics</a>, have_one is not correct based on where I put the associating key.</p> <p>You can think of it as every time you get a new passport, the physical passport is changing (with its issuing and expiry date changing) but it is still a passport. Thus, you can have a lot of physical passports (certificates) but you only have 1 present passport (the last in the series, which is a physical passport) and the physical passports belong to the "passport" class of IDs (certificate series).</p> <p>What I want is that I can call CertificateSeries.last_certificate_in_series and it will return the last certificate in the series. I thought of doing this in the db level by having the field last_certificate_in_series_id. I wanted to do it this way to reduce the database overhead of just getting the last one in the series. The other approach I thought of was get all the certificates in a series, arrange them by date, and get the most recent one.</p> <p>Thus I'm now having problems trying to reflect this association in the models.</p> <pre><code>belongs_to :last_certificate_in_series, :class_name =&gt; "Certificate", :foreign_key =&gt; :last_certificate_in_series_id </code></pre> <p>seems not to define it properly. I can call CertificateSeries.last_certificate_in_series but it only returns a nilClass even when last_certificate_in_series_id is set to a valid value.</p> <p>I'm open for suggestions on other approaches.</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