Jack Moody
Jack Moody

Reputation: 1771

How to create select tag in form_for Rails

I am trying to create a select tag in a form_for where I can select multiple categories from the options. I have looked at the Rails documentation and this SO, but neither of them seem to work. So far, I have this:

<select class="selectpicker" data-style="form-control" multiple title="Choose Department(s)" data-size="5">
   <%= options_from_collection_for_select(Category.all, :id, :name)%>
</select>

And my form_for looks like this:

<%= form_for(@listing, :html => {class: "form-horizontal" , role: "form"}) do |f| %>

My listings can have many categories. How am I supposed to make this save to my form? Right now, the categories aren't saving when I submit my form.

Upvotes: 0

Views: 2837

Answers (2)

Jack Moody
Jack Moody

Reputation: 1771

Final answer ended up being <%= f.collection_select(:category_ids, Category.all, :id, :name,{:"data-style" => "form-control", :"data-size" => "5"}, {class: "selectpicker", title: "Choose Department(s)", multiple: true}) %> as mmichael pointed out.

Upvotes: 0

vich
vich

Reputation: 11896

It's not working because your select isn't scoped to your @listing object. Try:

<%= f.collection_select(:category_id, Category.all, :id, :name) %>

To address @ddubs's comment suggesting to replace the select tag with a Rails form helper as well as keeping your custom HTML data attributes:

<%= f.collection_select(:category_ids, Category.all, :id, :name, {}, class: "selectpicker", title: "Choose Department(s)", multiple: true, data: { style: "form-control", size: "5" }) %>

For more information on collection_select options, look at the Rails api.

Upvotes: 2

Related Questions