【发布时间】:2017-05-21 14:09:00
【问题描述】:
给定以下模型:
ServiceCenter
has_many :country_codes
CountryCode
belongs_to :service_center
什么是 ActiveRecord 查询,它将返回如下内容:
{
"US": ["United States"],
"PT": ["Portugal", "Spain", "Estonia"],
"FR": ["France", "Germany", "Austria"]
}
其中键是每个 ServiceCenter 的 country 属性,值是属于它的每个 CountryCode 的 country_name 属性? 换句话说,我只想要一个列表CountryCodes 属于每个 ServiceCenter,只显示那些属性。
{ 'service_centers.country': 'country_code.country_name', 'country_code.country_name' }
我试过这个:
CountryCode
.joins(:service_center)
.select('country_codes.country_name', 'service_centers.country')
.group('service_centers.country')
但这会返回:
<ActiveRecord::Relation [
<CountryCode id: nil, country_name: "Portugal">,
<CountryCode id: nil, country_name: "United States">,
<CountryCode id: nil, country_name: "Portugal">.....]>
我也尝试了ServiceCenter.joins(:country_code)....,但结果相似——ActiveRecord 与 ID 为 nil 的 ServiceCenter 对象的关系,并给出了 country 属性。
我看过与此类似的答案:Get all records grouped by field from association and sorted by count in group,但我不想数。
如果有任何帮助,我将不胜感激!
【问题讨论】:
-
在mysql数据库中很难完全实现,它没有array/hstore数据类型(像postgresql一样),所以你不能对hash-like数据结构进行转换。
-
啊,也许这就是我所缺少的。我有一种感觉,我知道这是可能的,而且我以前见过类似的东西,但可能是使用 Postgresql。
标签: ruby-on-rails-4 activerecord mysql2