2013-03-04 57 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")