THpubs
THpubs

Reputation: 8172

When using arrays as the data type in a Rails model, in the form field I get empty curly brackets `{}`

Now we can set array as the data type in Rails. So here's how I set an array in my database :

t.string :tags, array: true,default: []

Now in the form, I get empty curly brackets {}. If I remove the curly brackets the system won't accept it. It asks for the brackets. When editing also I see the curly brackets with the tags. How to remove it?

The view :

<%= f.label :tags, 'Tags :' ,class: "updLbl" %>
<%= f.text_field :tags, class: "updInp" %>

Upvotes: 4

Views: 1253

Answers (3)

Mohamed Yakout
Mohamed Yakout

Reputation: 3036

Quick solution

You can use multiple select as the following:

f.select :tags, @model.tags, {include_blank: 'Please Select'}, {multiple: true, class: 'selectpicker chosen-select'}

Or use join method for array, to return string separated with special string as the following:

<%= f.text_field :tags, class: "updInp", value: @model.tags.join(,) %>

Fix your database

I suggest ti fix your database, and use t.column instead of using t.string as the following:

t.column :tags, array: true,default: []

So I recommend to read about method-i-column, and this useful answer.

Upvotes: 4

Arkhitech
Arkhitech

Reputation: 475

You can define array as data type, but you still are responsible for its presentation in view and how you customize it for your needs. One simplification is to just join the tags and show them in a comma-separated way.

Another option is to have a text field defined for each array value (tag) and then use javascript to add more text fields if more tags are to be inserted. To simplify the process, you can use SimpleForm, and define your own custom input in a way similar to the one defined at: http://railsguides.net/simple-form-array-text-input/

Upvotes: 1

ppascualv
ppascualv

Reputation: 1137

With this line you add value to value field of text_field, with this method you can use all methods of array.

<%= f.text_field :tags, class: "updInp", value: @model.tags.join(,) %>

Hope it helps

Upvotes: 0

Related Questions