簡體   English   中英

在 Rails 中使用帶有 Postgres HSTORE 的商店

[英]Using a store with Postgres HSTORE in Rails

我有一個帶有數據庫字段'remark'用戶模型。 我使用 Postgres 作為數據庫,“備注”字段的類型為HSTORE 因此,'remark' 存儲帶有額外用戶信息的哈希值。

正如某人所建議的那樣,我在“用戶”模型中添加了一個商店,如下所示:

class User < ActiveRecord::Base
  store :remark, accessors: [ :info ]
  #some code
end

現在我可以通過使用這個訪問器'@user.info'來獲取@user.remark['info'] 中的值。 這很好用。 但是當我嘗試設置並保存這樣的新值時:

@user.info = "some info"
@user.save

我收到以下錯誤:

ActiveRecord::StatementInvalid: PG::InternalError: ERROR:  Syntax error near '!' at position 4

是否可以通過這種方式使用 HSTORE 類型的數據庫字段? 我究竟做錯了什么?

添加自定義編碼器以存儲

class User < ActiveRecord::Base
  store :remark, accessors: [ :info ], coder: HstoreCoder
  #some code
end

HstoreCoder類:

class HstoreCoder
  class << self
    def load(hash)
      hash
    end

    def dump(value)
      value.to_hash
    end
  end
end

它應該有幫助。

對於 Rails 5 和 hstore,使用store_accessor而不是store

store_accessor :remark, :info

注意:如果您使用 PostgreSQL 特定的列,如 hstore 或 json,則不需要 .store 提供的序列化。 只需使用 .store_accessor 來生成訪問器方法。 請注意,這些列使用字符串鍵控哈希,並且不允許使用符號訪問。

https://api.rubyonrails.org/classes/ActiveRecord/Store.html

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM