0

组我有名字的“审核”模式:字符串数据:hstore属性 - 如下:Rails和Postgres的,由hstore

#<Audit 
id: 1, 
name: "my audit", 
data: {"publisher"=>"some publisher", "display_version"=>"17.012.20098"}, 
created_at: "2017-10-10 13:09:56", 
updated_at: "2017-10-10 13:09:56"> 

我想产生一个包含3列的报告: 名,display_version,算上

为了实现这一点,我认为我需要按“名”和“数据 - >‘display_version’”

我与查询和AR语法挣扎。

我至今是:

Parent.audits.group(:name, :data -> 'display_version)' 

即使这是行不通的。有人可以帮忙吗?我没有找到任何运气的例子。

回答

0

使用jsonb而不是hstore(对于各种原因)

'审计' 模型名称:字符串和数据:jsonb

Audit.rb

store_accessor :data, :publisher, :display_version 

然后尝试:

Parent.audits.pluck(:name, :publisher, :display_version) 

Good Resource on JSONB and Postgresql

hstore columns don’t allow a nested structure; they also store all values as strings, which will require type coercion on both database and application layers. With json/jsonb columns you don’t have this problem; numbers (integers/float), booleans, arrays, strings and nulls are accepted, and you can even nest structures in any way you want.

The recommendation is that you stop using hstore in favor of jsonb; just remember that you have to use PostgreSQL 9.4+ for this to work.

+0

有用的信息,但它并没有回答这个问题。 – user3565039

0

您可以通过包含SQL分组表达式group一个字符串,所以你可以说:

Parent.audits.group(%q{name, data -> 'display_version'}) 

或:

Parent.audits.group(%q{audits.name, audits.data -> 'display_version'}) 

然后你可以扔在年底#count调用来得到你想要的数据:

Parent.audits.group(%q{name, data -> 'display_version'}).count 
+0

谢谢。这产生:ActiveRecord :: StatementInvalid:PG :: GroupingError:错误:列“audits.id”必须出现在GROUP BY子句中或用于聚合函数 – user3565039

+0

对不起,错过了'count'。我刚刚更新了答案。 –