A
A
Art Snail2016-12-24 13:13:26
PostgreSQL
Art Snail, 2016-12-24 13:13:26

How to properly update postgresql array in Rails?

There is a table, one of the fields is an array
: string, array: true
I use form_for, for this field I use f.text_field
When creating a new object, I pass data to this field in the form: {one, two}
The array is saved.
But when editing the object, the following value is substituted into this field: one two
After I edit another field and save the changes, the value: one two is passed to the array field, as a result of which an empty array is saved.
What am I doing wrong?
Maybe you need to use some other helper, and not f.text_field?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Andrey Demidenko, 2016-12-24
@artsnail

Text_field is also possible, You just need to add additional methods, Let's assume that we have a names field

class User < ApplicationRecord
  def names_list
    names.join(', ')
  end

  def names_list=(new_value)
    self.names = new_value.split(/,\s+/)
  end
end

And the corresponding one is somewhere in the form, we update it separated by commas in this case, but this is already as you want
and do not forget to change it to the controller
params.require(:user).permit(:names_list)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question