【问题标题】:Newbie confusion on hstore joins with railshstore 上的新手困惑加入了 rails
【发布时间】:2013-03-04 22:25:17
【问题描述】:

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

所以我有两条路:

  • 编写引用数据库视图的 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


    【解决方案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")
    

    【讨论】:

      猜你喜欢
      • 2022-10-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-03-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多