13
votes

I am using SimpleForm to build my form.

I have say the following model:

class ScheduledContent < ActiveRecord::Base
    belongs_to :parent
    attr_accessible :lots, :of, :other, :fields
    serialize :schedule, Array
end

I want to construct a form, where among many other fields and associations (this model is actually part of a has_many association already - so quite a complex form) a user is presented with a variable number of days (eg Day 1, Day 2, Day 3, etc) - and each day can be checked or unchecked. So if a user checks Day 1, and Day 5 say - I want to store [1, 5] in the schedule field. Before the form - I can construct a simple array of possible days to choose from, including obviously the days already chosen.

What is the best way to represent this form using SimpleForm's form helpers? If it is not possible to do so - I could use Rails' form helpers too to make it work, but my preference is SimpleForm as the rest of the form is already constructed using SimpleForm.

3

3 Answers

27
votes

Yes, you can do it with SimpleForm. Here is an example:

<%= simple_form_for(@user) do |f| %>
  <%= f.input :schedule, as: :check_boxes, collection: [['Day 1', 1], ['Day 2', 2]] %>
  <%= f.button :submit %>
<% end %>
5
votes

Answer to an old question, but I had to do something similar recently. To mark already-selected check box options, I used :checked similar to this:

<%=
  form.input :schedule, {
    as:         :check_boxes,
    collection: Days.my_scope.map { |day| [day.name, day.id] },
    wrapper:    :vertical_radio_and_checkboxes,
    checked:    form.object.schedule
  }
%>
0
votes

Was struggling with this one as well. Finally made it as the haml code below. It makes use of SimpleForm collection_check_boxes method and will output check boxes with labels vertically. List will not show general label in top for the whole checkbox list.

= f.collection_check_boxes :schedule, Day.all, :id, :label_name do |day|
  = day.check_box
  = day.label
  %br