Search code examples
ruby-on-railspostgresqlhstore

Hstore doesn't update its values in rails


I have an issue with postgres hstore. I found out that before Rails 4.2. you need to use this code to save hstore:

var_will_change!
var[:foo] = 'boo'
var.save!

And this issue was here https://github.com/rails/rails/issues/6127.

In new rails there isn't such a problem with hstore. Even if you look at rails guides http://edgeguides.rubyonrails.org/active_record_postgresql.html#hstore. There's only var.save!. And I don't understand why it doesn't work with my code. I'm using rails 4.2.1. And here's my code:

def update
    album = Album.find(params[:id])

    users = User.where(email: params[:album][:emails])
    album.members.merge!(Hash[users.pluck(:id).zip params[:album][:roles]])

    album.save!

    render json: Hash[users.pluck(:name).zip params[:album][:roles]]
  end

In this code album.members is the wanted hstore to fix.

Oh and maybe this code can be upgraded in more simpler way. If you have those kind of suggestions I'd gladly hear them.
Thanks for answering.

EDIT: Found more specific error, when album tries to save I get this error 8991 segmentation fault (core dumped) rails s.


Solution

  • Well I managed to solve that question, if somebody gets into such trouble. It's like one of those fairy tales on the planet Ruby, where parents tell their kids the moral of the story: 'Kids don't forget to use parentheses whenever you can, just to make sure your code is right'.

    And the problem was as you've noticed with parentheses, I suppose it interpreted the method in some other way than needed.It's working like this:

    album.roles.merge!(Hash[users.pluck(:id).zip(params[:album][:roles])])