Rails 3 ActiveRecord Request

Considering the Rails 3 app with the following models:

# == 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 < ActiveRecord::Base

  belongs_to                          :user
  has_many                            :multipage_pdfs,  :as => :assetable,   :dependent => :destroy
  has_many                            :singlepage_pdfs, :as => :assetable,   :dependent => :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 < ActiveRecord::Base
  ...
end


class SinglepagePdf < Asset
  ...
end

the asset of # version is incremented every time a new asset is created, if an object with the same name exists, so my assets usually look (simplified):

    | 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 |

Now I need to get all singlepage_pdfs of the same order, but only the latest version for each name. How can i achieve this?

o = Order.find(1)
singlepage_pdfs = o.singlepage_pdfs.find(...)

3 4...

+3
2

, singlepage_pdfs

o.singlepage_pdfs.group("name").order("version DESC")
0

-,, , . , , - :

Order has_many Asset belongs_to Assetable(polymorphic)

Order ( has_many :through).

-,, , , - . :

0

All Articles