2013-03-04 63 views
0

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

所以我有两条路:

  • 写轨道控制器参考,数据库
  • 上ncing一个VIEW写一些轨道喜欢使用包括查询,加入等

我真的喜欢做后者。然而,我对使用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

我可能是错的,但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")