Search code examples
ruby-on-railsformsnested-formsfields-for

Select multiple categories in form (rails)


I've got this tripbuilder which i want to assign categories to. So I've set up the models as where a trip can have any(or more) categories that are in the category table in my database. However; i have no idea how i can set up the form allowing a user to select categories via checkbox. Since fields_for doesn't sound like a solid way to go in this case (Because i want to see all the categories with a checkbox and select as many categories as i want). Can anyone help me out?

I've tried this form:

<%= form_for @trip, :html => {:multipart => true} do |a| %> 
    <%= a.label :title, "Routetitel" %>
    <%= a.text_field :title %>

    <%= a.label :description, "Omschrijving" %>
    <%= a.text_area :description %>

    <%= a.fields_for :categories do |cat| %>
        <%= cat.check_box :name %>
    <% end %>

    <%= a.submit 'Verstuur' %>
<% end %>

Solution

  • At first, you need to setup the relationship between trip and category like this:

    class Trip < ActiveRecord::Base
      has_and_belongs_to_many :categories
    end
    

    Then you can build the form like this:

    <%= form_for @trip, :html => {:multipart => true} do |a| %> 
        <%= a.label :title, "Routetitel" %>
        <%= a.text_field :title %>
    
        <%= a.label :description, "Omschrijving" %>
        <%= a.text_area :description %>
    
        <% Category.all.each do |cat| %>
            <%= check_box_tag "trip[category_ids][]", cat.id, @trip.catergory_ids.include?(cat.id)
        <% end %>
    
        <%= a.submit 'Verstuur' %>
    <% end %>