0

我有两个基于 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  
4

1 回答 1

1

我可能错了,但 ActiveRecord 的理念是为数据库创建一个公共层,并且该查询与 postgres 非常相关,具有序列化的内部连接。

您可以编写一个原始查询来执行此操作:

Device.find_by_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")
于 2013-03-04T22:43:52.513 回答