【问题标题】:Rails 3 ActiveRecord queryRails 3 ActiveRecord 查询
【发布时间】:2011-05-24 11:44:18
【问题描述】:

给定一个具有以下模型的 Rails 3 应用程序:

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

asset#version 每次创建新资产时都会增加,如果存在具有相同名称的资产,那么这就是我的资产通常的样子(简化):

|编号 |资产ID |资产类型 |姓名 |版本 |类型 | | 1 | 1 |订购 |我的.pdf | 1 |单页PDF | | 2 | 1 |订购 |我的.pdf | 2 |单页PDF | | 3 | 1 |订购 |我的.pdf | 3 |单页PDF | | 4 | 1 |订购 | bla.pdf | 1 |单页PDF |

现在我需要获取单个订单的所有 singlepage_pdf,但只有每个名称的最后一个版本。我怎样才能做到这一点?

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

结果应该只包含 id 为 3 和 4 的资产...

【问题讨论】:

    标签: ruby-on-rails activerecord


    【解决方案1】:

    试试这个,它按名称对所有 singlepage_pdf 进行分组并返回每个的最新版本

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

    【讨论】:

    • 感谢您的回答。我收到此错误:Column 'asset_id' must be present within GROUP_BY Clause。也许值得一提的是我正在使用 PostgreSQL...
    【解决方案2】:

    首先,我不确定您的关联设置是否正确。您可能需要引入另一层,这样您就有了类似的东西:

    Order has_many Asset belongs_to Assetable(polymorphic)
    

    然后您可以为Order 模型中的每个资产类型定义范围关联(通过has_many :through)。

    其次,就您进行版本控制的方式而言,我强烈建议您采用不同的方式并使用已建立的机制来执行此操作。为您处理此问题的示例库:

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-12-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多