Reputation: 3489
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 %>
Upvotes: 0
Views: 1905
Reputation: 5294
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 %>
Upvotes: 1
Reputation: 51
Please Modify your fields_for as described below and check !!!!
<%= a.fields_for "categories[]" do |cat| %>
<%= cat.check_box :name %>
<% end %>
Upvotes: 0
Reputation: 6030
Yes, it can be done by using select tag and multiple
attribute of select tag.
<% = a.select :categories, Category.all.collect {|c| [c.name, c.id]}, :include_blank => true', :multiple => "multiple" %>
Upvotes: 0