我有两个基于 postgres hstore 的表,entity
并且info
,它们看起来都像这样:
Column | Type | Modifiers
------------+--------------------------+---------------------------------------------------------------
id | integer | not null default nextval('entity__entities_id_seq'::regclass)
created_at | timestamp with time zone | not null
updated_at | timestamp with time zone | not null
context | hstore | default hstore((ARRAY[]::character varying[])::text[])
data | hstore | default hstore((ARRAY[]::character varying[])::text[])
所以我想要执行的 SQL 查询是这样的:
SELECT e.context->'device' AS device, i.data->'location' AS location from entity AS e
LEFT JOIN info AS i ON e.context->'device' = i.context->'device'
WHERE e.data->'type'='chassis
所以我有两条路:
- 编写在数据库上引用 VIEW 的 rails 控制器
- 使用include,join等编写一些rails,例如查询。
我真的更愿意做后者。但是,对于要使用的 Rails 代码,我完全感到困惑。
我的模型是(我知道我错过了belongs_to
等,但我不知道如何与 hstore 字段建立关系):
class Device < ActiveRecord::Base
self.table_name = 'entity'
self.primary_key = 'id'
attr_accessible :id, :created_at, :updated_at, :context, :data
serialize :context, ActiveRecord::Coders::Hstore
serialize :data, ActiveRecord::Coders::Hstore
end
class DeviceInfo < ActiveRecord::Base
self.table_name = 'info'
self.primary_key = 'id'
attr_accessible :id, :created_at, :updated_at, :context, :data
serialize :context, ActiveRecord::Coders::Hstore
serialize :data, ActiveRecord::Coders::Hstore
end