1

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?

2
  • 1
    I had put the ruby-on-rails-4 tag because the .update syntax is different for earlier versions (I think). Commented Jan 7, 2014 at 1:04
  • 1
    I've reverted the tag cancellation. update in Rails 4 is the same of update_attributes before, but I agree the tags makes sense here. Sorry for the change. Commented Jan 7, 2014 at 1:05

1 Answer 1

2

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"
Sign up to request clarification or add additional context in comments.

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.