Search code examples
ruby-on-railspostgresqlactiverecord

Can I use an attr_writer with a Postgres Array?


I have a collection of checkboxes that save an array of responses to the database, in a Postgres array column. The problem is that unchecked options come through as empty strings, so I end up with

['a', '', 'c']

If I try to setup an attr_writer to clean the array on save:

def multiple_response=(val)
  val.compact_blank
end

or even just

attr_writer :multiple_response

Then nothing is saved to the database. What am I doing wrong?


Solution

  • This is what you need, after removing blanks, you should call super, ActiveRecord's method for saving the attribute:

    def multiple_response=(val)
      super(val.compact_blank)
    end