【发布时间】:2013-03-04 22:25:17
【问题描述】:
我有两个基于 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
所以我有两条路:
- 编写引用数据库视图的 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
【问题讨论】:
标签: ruby-on-rails postgresql model controller hstore