Alexander Popov
Alexander Popov

Reputation: 24875

How to submit an array of integers in a Rails form?

I would like to know if there is a way to have some sort of input field in a Rails form, so that if the user enters 1, 2, 3, then params[:model][:attribute] returns [1, 2, 3] or at least ['1', '2', '3'], but not ['1, 2, 3'].

Background:

I have a model Foo, which has an attribute bar_ids. The datatype of this attribute in the PostgresQL database is Array. I've tried several things:

So, again my question - is there a way to construct my form in such a way, so that Rails automatically parses the input to the respective datatype, in my case - an array of integers?

Upvotes: 1

Views: 1521

Answers (1)

Oleg K.
Oleg K.

Reputation: 1549

People usually edit the params manually before updating the model:

 params[:model][:attribute] = params[:model:][:attribute].split(',')
 # ...
 Model.update_attributes(params[:model])

It is usually done in controller action or in before_action.

Upvotes: 3

Related Questions