新手对hstore的困惑加入了rails

时间:2013-03-04 22:25:17

标签: ruby-on-rails postgresql model controller hstore

我有两个基于postgres hstore的表,entityinfo,两者都是这样的:

   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代码感到困惑。

我的模型是(我知道我缺少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  

1 个答案:

答案 0 :(得分: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")