Rails 4 checkboxes of strings never return an empty array
arrays, checkbox, ruby-on-rails, string
Solution
When you don't check any checkboxes and submit the form, the content of params is lacking a value saying "none was checked". It just avoid submitting `nil` values for the inputs.
A simple way to solve this, is to set the value of the relevant `params` if not set before:
Rails 4:
# your_model controller
def your_model_params # redefining the Strong Params
params[:your_model][:disposizione_campionamento] ||= []
params.permit(:whatever).require(:another)
end
Rails 3:
# your_model controller
before_filter :set_disposizione_campionamento, only: [:update, :create]
def set_disposizione_campionamento
params[:your_model][:disposizione_campionamento] ||= []
end
Problem
I have an array of strings that is the result of a multiple-choice checkbox, when there is no choice in the checkbox the array doesn't change and the result is the last array saved! I'd like to show something like " " when the checkbox has no value selected. ``` <%= f.label :disposizione_campionamento,"Disposizione" %> Random <%= f.check_box :disposizione_campionamento, { :multiple => true }, "Random", nil %> Sistematica <%= f.check_box :disposizione_campionamento,{ :multiple => true }, "Sistematica", nil %> Stratificata <%= f.check_box :disposizione_campionamento,{ :multiple => true }, "Stratificata",nil %><br/> ``` and in the model ``` serialize :disposizione_campionamento, Array ``` If i check Random,Sistematica and Stratificata the result is "Random,Sistematica,Stratificata" as I want but if I modify the array unchecking all the three values the result is ever "Random,Sistematica,Stratificata" when I submit the form I have this in the controller: ``` def create modulo2 = Modulo2.find(params[:modulo2_id]) @variabili = modulo2.variabilis.create(params[:id]) respond_to do |format| if @variabili.save format.html { redirect_to(modulo2_variabilis_path, :notice => 'Modifica effettuata') } format.xml { render :xml => @variabili, :status => :created, :location => [@variabili.modulo2, @variabili] } else format.html { render :action => "new" } format.xml { render :xml => @variabili.errors, :status => :unprocessable_entity } ``` disposizione_campionamento is an attribute of "variabili" that is a nested attribute of "modulo2"