2

I have an array field in one of my models, with elements being symbols. For example, here is how I assign values to this field:

Model.field = [:a, :b, :c]

I use Postgres so I store these arrays in an array column. The problem is that Rails automatically serializes the symbols from the given array to strings when saving them to the database, but doesn't convert them back to symbols when objects are fetched from the database. How can I tell my model to automatically convert array values to symbols?

2
  • Oh I see what you mean. I'll delete my answer as you need an "automatic" way of doing it. Commented Nov 22, 2015 at 15:18
  • Indeed. I am thinking about using serialize :field, Serializer, but I guess that Serializer already exists for my needs. Commented Nov 22, 2015 at 16:06

1 Answer 1

1

You could try overriding the attribute reader method and doing the datatype conversion there

class Model < ActiveRecord::Base
  # ...

  def field
    self[:field].map(&:to_sym)
  end
end
Sign up to request clarification or add additional context in comments.

1 Comment

I prefer not to, since I will have a hard time dealing with other ActiveRecord goodies (such as attributes).

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.