4

I have a form (form_for) and I want the user to be able to select multiple "categories" using the select method.

= form_for @place, :url=>{:action=>"#"} do |f|
  #appended_wrapper
  .categories
    = f.label :categories, "Categories: "
    = f.select :categories, %w(Active Art Auto Food), {:include_blank => true}
  = f.submit "Submit"

Everytime the user selects a category, I have jQuery append a div with the value of the category so that users can see and remove the categories they've added.

$('#hotel_categories').change(function(){
  value = $(this).val();
  $('#appended_wrapper').append( '<div class="appended"> '+value+' <a class="remove" href="#">Remove</a></div>' );

  $('.remove').click(function(){
    $(this).parent(".appended").remove();
  });

});

When I press the submit button, I want all the selected categories to be passed to my controller in an array.

How do I achieve this?

Thanks.

1 Answer 1

3

Inside your div, add a hidden input field like this one:

<input name="category_ids[]" type="hidden" value="1">

The value represents the id of the category. Notice the square brackets next to category_ids. All the hidden inputs have to have exactly the same name.

The values will come through as an array in the params hash in your controller.

Sign up to request clarification or add additional context in comments.

4 Comments

I am going to try this. Will get back to you guys.
Can the value simply be the actual string (i.e. "Active" or "Food") instead of the id of the category?
Thanks - this worked and rails recognizes the multiple selection as an array in the params hash!
@hyngyn yes, the value can be whatever you want it to be. It will all come through as strings anyway.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.