Fellow Stranger
Fellow Stranger

Reputation: 34013

Update attribute with array insertion

I have an Impression model with an actions attribute that is serialized for Array.

class Impression < ActiveRecord::Base
  serialize :actions, Array
end

Normal attribute updating procedure:
impression.update(some_attr: "new_value")

Normal array insertion procedure:
impression.actions << "new_value"
impression.save

Is there a way to insert a new value to an array attribute that works like the .update method, i.e. in one single expression?

Upvotes: 1

Views: 1584

Answers (1)

Simone Carletti
Simone Carletti

Reputation: 176362

No, this is not possible when using the ActiveRecord serialization feature because the serialization/deserialization must be controller by ActiveRecord and update performs a direct SQL update call on the database.

Some non-relational database (such as MongoDB) offers this feature because they are designed in order to do so. PostgreSQL provides a Hash extension you can install that would allow you to perform direct operations on the serialized field.

In all the other cases, you could potentially update the field directly, but I don't encourage you to do so. There is a potential risk to write corrupted data.

Instead, I suggest you to create a custom method that performs both the push and save. In any case, this is a good idea because you are exposing a custom API outside the model instead of coupling your model to the ActiveRecord architecture.

class Impression < ActiveRecord::Base
  serialize :actions, Array

  def add_action(action)
    self.actions << action
    self.save
  end
end

The you can use

impression = ...
impression.add_action "new_value"

Upvotes: 2

Related Questions