[英]Using a store with Postgres HSTORE in Rails
I have a User Model with a database field 'remark' .我有一个带有数据库字段'remark'的用户模型。 I am using Postgres as Database and the 'remark' field is of type HSTORE .我使用 Postgres 作为数据库,“备注”字段的类型为HSTORE 。 So 'remark' stores a hash with extra user information.因此,'remark' 存储带有额外用户信息的哈希值。
As suggested by someone I added a store to my 'User' model like this:正如某人所建议的那样,我在“用户”模型中添加了一个商店,如下所示:
class User < ActiveRecord::Base
store :remark, accessors: [ :info ]
#some code
end
Now I can get the value in @user.remark['info'] by using this accessor '@user.info' .现在我可以通过使用这个访问器'@user.info'来获取@user.remark['info'] 中的值。 That works fine.这很好用。 But when I try to set and save a new value like this:但是当我尝试设置并保存这样的新值时:
@user.info = "some info"
@user.save
I get the following error:我收到以下错误:
ActiveRecord::StatementInvalid: PG::InternalError: ERROR: Syntax error near '!' at position 4
Is it possible to use a HSTORE type databasefield this way?是否可以通过这种方式使用 HSTORE 类型的数据库字段? What am I doing wrong?我究竟做错了什么?
Add a custom coder to store :添加自定义编码器以存储:
class User < ActiveRecord::Base
store :remark, accessors: [ :info ], coder: HstoreCoder
#some code
end
HstoreCoder class: HstoreCoder类:
class HstoreCoder
class << self
def load(hash)
hash
end
def dump(value)
value.to_hash
end
end
end
It should help.它应该有帮助。
For Rails 5 and hstore use store_accessor
instead of store
对于 Rails 5 和 hstore,使用store_accessor
而不是store
store_accessor :remark, :info
NOTE: If you are using PostgreSQL specific columns like hstore or json there is no need for the serialization provided by .store.注意:如果您使用 PostgreSQL 特定的列,如 hstore 或 json,则不需要 .store 提供的序列化。 Simply use .store_accessor instead to generate the accessor methods.只需使用 .store_accessor 来生成访问器方法。 Be aware that these columns use a string keyed hash and do not allow access using a symbol.请注意,这些列使用字符串键控哈希,并且不允许使用符号访问。
https://api.rubyonrails.org/classes/ActiveRecord/Store.html https://api.rubyonrails.org/classes/ActiveRecord/Store.html
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.