Note that there are some explanatory texts on larger screens.

plurals
  1. PORails 3 ActiveRecord query
    text
    copied!<p>Given a Rails 3 app with the following models:</p> <pre class="lang-rb prettyprint-override"><code># == Schema Information # Schema version: 20110517144920 # # Table name: orders # # id :integer not null, primary key # user_id :integer not null # name :string(255) not null # state :string(255) # created_at :datetime # updated_at :datetime # class Order &lt; ActiveRecord::Base belongs_to :user has_many :multipage_pdfs, :as =&gt; :assetable, :dependent =&gt; :destroy has_many :singlepage_pdfs, :as =&gt; :assetable, :dependent =&gt; :destroy ... end # == Schema Information # Schema version: 20110511064747 # # Table name: assets # # id :integer not null, primary key # assetable_id :integer not null # assetable_type :string(255) not null # state :string(255) # type :string(255) not null # name :string(255) not null # document :string(255) not null # version :integer default(0), not null # created_at :datetime # updated_at :datetime # class Asset &lt; ActiveRecord::Base ... end class SinglepagePdf &lt; Asset ... end </code></pre> <p>asset#version is increased each time a new asset is created, if an asset with an identical name exists, so that's what my assets typically look like (simplified):</p> <pre> | id | assetable_id | assetable_type | name | version | type | | 1 | 1 | Order | my.pdf | 1 | SinglepagePdf | | 2 | 1 | Order | my.pdf | 2 | SinglepagePdf | | 3 | 1 | Order | my.pdf | 3 | SinglepagePdf | | 4 | 1 | Order | bla.pdf | 1 | SinglepagePdf | </pre> <p>Now i need to get all singlepage_pdfs of a single order, but only the last version for each name. How can i achieve this?</p> <pre class="lang-rb prettyprint-override"><code>o = Order.find(1) singlepage_pdfs = o.singlepage_pdfs.find(...) </code></pre> <p>The result should contain only contain the Assets with id 3 and 4...</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