Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>The Rails way to do this is a named scope on pets.</p> <p>Something like this:</p> <pre><code>class Pets has_many :pet_names has_many :names, :through =&gt; :pet_names named_scope :with_current_name, lambda {|name| { :joins =&gt; "JOIN (pet_names pna, names) " + "ON (pna.pet_id = pets.id AND pna.name_id = names.id) " + "LEFT JOIN pet_names pnb " + "ON (pnb.pet_id = pets.id AND pna.created_at &lt; pnb.created_at)", :conditions =&gt; ["pnb.id IS NULL AND names.id = ? ", name] } } end Pets.with_current_name(@name) @name.pets.with_current_name(@name) </code></pre> <p>To keep things name centric you could always define a method on C/Name that invokes the named scope.</p> <p>You could always do </p> <pre><code>class Name &lt; ActiveRecord::Base has_many :pet_names has_many :pets, :through =&gt; :pet_names def currently_named_pets Pets.with_current_name(self) end end </code></pre> <p>And </p> <pre><code>@name.currently_named_pets </code></pre> <p>It's a pretty complicated join. Which is an indicator that you should probably should rethink the way you store this information. Why is it so important that Names be in a separate table? </p> <p>You might be better off doing something like this:</p> <p>After adding <code>name</code> and <code>old_name</code> columns to Pet:</p> <pre><code>class Pet &lt; ActiveRecord::Base serialize :old_name, Array def after_initialization @old_name ||= [] end def name= new_name self.old_name &lt;&lt; new_name self.name = new_name end named_scope :with_name, lambda {|name| { :conditions =&gt; {:name =&gt; name}} } end </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