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?
One of these column types is called hstore, a column based on a key-value data structure. This feature is extremely useful when you have a data structure that can vary, but that needs to be queried eventually. In Rails you can use serialized attributes, but this approach has a problem: you can’t query the stored value.
Querying data from an hstore column is similar to querying data from a column with native data type using the SELECT statement as follows: Postgresql hstore provides the -> operator to query the value of a specific key from an hstore column.
In Rails you can use serialized attributes, but this approach has a problem: you can’t query the stored value. This is not the case with hstore, since you can use functions and operators to query values and keys. The downside of hstore is that all values are stored as strings.
Updates the attributes directly in the database issuing an UPDATE SQL statement and sets them in the receiver: This is the fastest way to update attributes because it goes straight to the database, but take into account that in consequence the regular update procedures are totally bypassed.
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' }) )
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With