Rails simple_form checkboxes for serialized Array field
Asked Answered
P

3

16

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.

Pappose answered 12/12, 2012 at 6:4 Comment(0)
V
28

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 %>
Variscite answered 12/12, 2012 at 18:36 Comment(4)
Yes - this works for me. Is there a way to also say which check boxes are already selected?Pappose
hrm, what do you mean? When do you need this to know? and why?Variscite
I want to know - well the user would want to know - which days are already 'selected' in the :schedule. This form appears on both a new and an edit screen.Pappose
hmmm, but if you set @user.schedule = [1] then you'll get a form with checked Day 1 checkbox. Is not that you want?Variscite
E
5

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
  }
%>
Eberto answered 18/8, 2016 at 0:45 Comment(0)
M
0

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
Mazer answered 21/8, 2021 at 15:6 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.