Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Simple form multiple select with simple array

Using this line of code:

<%= m.input :battery, :collection => ["1","2","3","4"], :input_html => { :multiple => true } %>

I see a perfectly rendered multi-select menu in my form.

However, when I submit the form (after selecting 1 and 2) I receive the following:

1.9.3p374 :012 > Style.find(402).battery
  Style Load (1.8ms)  SELECT `styles`.* FROM `styles` WHERE `styles`.`id` = 402 LIMIT 1
 => "---\n- ''\n- '1'\n- '2'\n" 

Now when I reload the Style edit form, nothing is selected in the multi-select, and if I resubmit, my previous selections are overwritten:

=> "---\n- ''\n" 

Obviously the format being used is not being interpretted correctly by the form

Controller update action

@style = Style.find(params[:id]) 
@style.update_attributes(params[:style])

Params hash

"battery"=>["", "1", "2"]

UPDATE

After adding serialize :battery, Array to my style model I am now seeing:

Style Load (0.1ms)  SELECT `styles`.* FROM `styles` WHERE `styles`.`id` = 402 LIMIT 1
 => ["", "1", "2"] 

Most importantly, the form is loading the DB data now.

like image 843
Abram Avatar asked Sep 14 '26 10:09

Abram


1 Answers

If you want to save an array in your battery field u can use

serialize :battery, Array

in model

like image 127
Oleg Haidul Avatar answered Sep 16 '26 06:09

Oleg Haidul