ProGM
ProGM

Reputation: 7108

Use update_columns on an hstore attribute

Is there an equivalent of update_columns for hstore attributes in rails 4?

My model is:

class Image < ActiveRecord::Base
  store_accessor :additions, :small, :medium, :big, :image_version
end

Assuming I want to update small.
I tried:

@image = Image.first
@image.update_columns(small: 'my_small_image')

But I receive, of course:

PG::UndefinedColumn: ERROR:  column "small" of relation "contents" does not exist
LINE 1: UPDATE "images" SET "small" = 'my_small_image' WHERE "imag...
                              ^
: UPDATE "images" SET "small" = 'my_small_image' WHERE "images"."id" = 1

Is there an easy way to do it?

EDIT: I can't use update_attributes, because I need to save only the passed arguments.

update_attributes calls save, and I don't want this, because it saves all other changed attributes, not only the one passed.

Example:

@image = Image.first
@image.big = 'fjdiosjfoa'
@image.update_attributes(small: 'my_small_image')

Both big and small are saved.

Instead, with update_columns, only small get saved. How to do it with an hstore?

Upvotes: 5

Views: 1230

Answers (2)

Ben
Ben

Reputation: 472

Use update_column but pass in the hstore attribute and a hash. To prevent any existing hstore values getting blown away, you need to merge the existing values:

@image.update_column(:additions, @image.additions.merge({ 'small' => 'my_small_image' }) )

Upvotes: 4

lx00st
lx00st

Reputation: 1596

Use update_attributes(small: 'my_small_image') if you want to save.

Use assign_attributes(small: 'my_small_image') if you dont want to save.

Upvotes: 2

Related Questions