Rails PostgreSQL 的 hstore 能实现关联吗?

KoALa · May 21, 2013 · Last by KoALa replied at May 21, 2013 · 3160 hits

大家好,最近刚接触 postgresql 以及 hstore,我想问大家通过 hstore 能实现普通的 active_record 中的那种关联吗?比如

class User < ActiveRecord::Base
  serialize :properties, ActiveRecord::Coders::Hstore
end

我想在 hstore 类型的 properties 中存放 key 为 department_id 的一个 hash,例如{department_id: 10}这样。 请问如何通过这个 department_id 关联找到对应的 department,像 active_record 中那样

class User < ActiveRecord::Base
  belongs_to :deparment
end

就可以使用User.find(xxx).deparment了? 还有这种应用场景是不是不适用 hstore?

不适合吧。

hstore 关联实现方法

def deparment
    Deparment.find(self. properties['deparment_id'])
end

#1 楼 @richfisher 这样子手工写我知道呀,我以为会有类似 AR 里那种 macro style 的写法...

You need to Sign in before reply, if you don't have an account, please Sign up first.