marcamillion
marcamillion

Reputation: 33755

How do I tell my simple_form object to return an array with just the selected IDs and not any empty values?

So I have a simple_form object that looks like this:

<%= f.input :parents, collection: (@node.family_tree.nodes - @node.parents - [@node]).uniq, as: :check_boxes, label: "Parent 1" %>

This produces HTML that looks like this:

<div class="node_parents">
<label>Parent 1</label>
<input id="node_parents_13" name="node[parents][]" type="checkbox" value="13" /><label>Jack</label>
<input id="node_parents_35" name="node[parents][]" type="checkbox" value="35" /><label>Testy</label>
<input id="node_parents_37" name="node[parents][]" type="checkbox" value="37" /><label>Resty</label>
<input id="node_parents_36" name="node[parents][]" type="checkbox" value="36" /><label>Mesty</label>
<input name="node[parents][]" type="hidden" value="" />
</div>

When I fill out 2 of the 4 objects, my log looks like this:

Parameters: {"utf8"=>"✓", "authenticity_token"=>"F1HGLwIjDG3VaIYlnsu7NbROEiWBO8xqJtjh5MreI9E=", "node"=>{"name"=>"Lesty", "parents"=>["13", "35", "", ""], "family_tree_id"=>"2"}, "commit"=>"Update Node", "id"=>"38"}

Rather than it sending the params[:parents] as a 4-element array with 2 empty/nil values, I would rather it just send a 2-element array.

How do I do that?

Upvotes: 0

Views: 142

Answers (2)

Sonalkumar sute
Sonalkumar sute

Reputation: 2575

Try this

params[:node][:parents].reject!{|p| p == ""} 

or

params[:node][:parents].reject!(&:blank?)

Upvotes: 1

Max Williams
Max Williams

Reputation: 32945

I don't know if you really need to change what is sent by the form, or if you can just filter out the blank values in the controller before doing anything with them?

If you do want to avoid sending empty values then you will need to do something with javascript on form submit, to alter the params from the form before they are submitted. It's definitely much simpler to let the form submit the blanks and filter them out in the controller, however.

To do it with javascript, you'll need to do something like this: i'm assuming you're using jQuery here. The approach i have chosen is to change the submit button so it calls a function instead of submitting the form. The function disables the empty inputs (thus not including them in the form data) and then submits the form.

Add a js function to the page

<script type="text/javascript">
  var processForm = function(){
    //disable unchecked checkboxes
    $("#myForm input[type=checkbox]").not(":checked").attr("disabled", "disabled");
    $("#myForm").submit();
  };
</script>

then replace your submit button with this:

<%= button_to_function "Submit", "processForm();" %>

Upvotes: 1

Related Questions