2

I have a User Model with a database field 'remark'. I am using Postgres as Database and the 'remark' field is of type HSTORE. So 'remark' stores a hash with extra user information.

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'. 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? What am I doing wrong?

4
  • The code you have posted looks okay. Are you sure the exception is coming from setting hstore values? Do you have any callbacks that might be throwing an error? What does the generated sql update command look like (try in console or look in your rails logs). Commented Sep 28, 2015 at 14:21
  • SQL (0.8ms) UPDATE "users" SET "remark" = $1, "updated_at" = $2 WHERE "users"."id" = $3 [["remark", "--- !ruby/hash:ActiveSupport::HashWithIndifferentAccess\ninfo: dit zou moeten werken\n"], ["updated_at", "2015-09-28 13:22:04.216668"], ["id", 1]] PG::InternalError: ERROR: Syntax error near '!' at position 4 : UPDATE "users" SET "remark" = $1, "updated_at" = $2 WHERE "users"."id" = $3 Commented Sep 28, 2015 at 14:30
  • Does it work with @user.remark['info'] = "some info"; @user.save? Commented Sep 28, 2015 at 20:21
  • no does'nt work either. I just saw that @user.save is not working. even if I don't change the instance. And When I delete the "store :remark, accessors: [ :info ]" from the model it does work. (using rails 4.2 and ruby2.1.1) Commented Sep 28, 2015 at 21:16

2 Answers 2

1

Add a custom coder to store:

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

HstoreCoder class:

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

    def dump(value)
      value.to_hash
    end
  end
end

It should help.

Sign up to request clarification or add additional context in comments.

Comments

0

For Rails 5 and hstore use store_accessor instead of 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. Simply use .store_accessor instead to generate the accessor methods. 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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.