如何根据列值分隔对象并检索和检索每个组的第一个对象?

时间:2016-08-23 21:04:41

标签: ruby-on-rails postgresql activerecord sqlite

我是一个相当新的编程,我无法找到问题的答案。我使用的是active record,rails和sqlite3,我有一个名为Unit的模型。这些单元具有多个列类别,已售出,颜色等,还有一个product_code,它对于前面提到的列中的每个唯一值组合都是唯一的。我不能做的是根据他们拥有的product_code分离所有单位,然后检索和对象(第一个或任何)。单位还需要在销售的列中具有错误值。我第一次尝试:

Unit.where(sold:false).select(:product_code).distinct

但这只给了我不同的代码:

#<ActiveRecord::Relation [#<Unit id: nil, product_code: "MONMJARD327">, 
#<Unit id: nil, product_code: "LAPEJARD327">, 
#<Unit id: nil, product_code: "ESTXJARD327">, 
#<Unit id: nil, product_code: "COSGJARD327">,
#<Unit id: nil, product_code: "BOLAJARD327">, 
#<Unit id: nil, product_code: "FUNIJARD327">, 
#<Unit id: nil, product_code: "CARMJARD327">, 
#<Unit id: nil, product_code: "MOCEJARD327">, 
#<Unit id: nil, product_code: "COJGJARD327">, 
#<Unit id: nil, product_code: "RELG">, ...]>

问题是我需要为每个不同的组检索列的值,以便我可以形成一个表。然后我尝试了这个:

Unit.where(sold:false).group(:product_code)

这在开发中运作良好:

[#<Unit id: 104, product_code: "BOLAJARD327", sold: false, category_id: 16, remission_id: nil, created_at: "2016-08-23 20:30:13", updated_at: "2016-08-23 20:30:13", fabric_id: 2, color_id: 1, pattern_id: 13, batch_id: nil, profit: nil, date_sold: nil, store_id: nil>, 
#<Unit id: 106, product_code: "CARMJARD327", sold: false, category_id: 11, remission_id: nil, created_at: "2016-08-23 20:30:13", updated_at: "2016-08-23 20:30:13", fabric_id: 2, color_id: 1, pattern_id: 13, batch_id: nil, profit: nil, date_sold: nil, store_id: nil>, etc.]

但在开发中我使用PosgresSQL,这会产生错误:

PG::GroupingError: ERROR:  column "units.id" must appear in the GROUP BY clause or be used in an aggregate function

有没有更好的方法来进行此选择并按预期检索对象?

提前致谢!

1 个答案:

答案 0 :(得分:0)

我不完全确定我明白你在这里要做什么,但是如果你想要包含产品代码的未售出单位的ActiveRecord关系,你可以这样做:

Unit.where(sold: false).select(:product_code)
# which returns
=> #<ActiveRecord::Relation [#<Unit id: nil, product_code: "ESTXJARD327">, #<Unit id: nil, product_code: "BOLAJARD327">]>

然后选择第一个你可以做的事情:

Unit.where(sold: false).select(:product_code).first

如果您有多个具有相同product_code的单位,则可以将它们组合在一起:

Unit.where(sold: false).select(:product_code).group(:product_code)

同样,您可以通过附加.first

在此处选择第一个条目