Rails simple_form checkboxes for serialized Array field

Joerg picture Joerg · Dec 12, 2012 · Viewed 12.6k times · Source

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.

Answer

Vasiliy Ermolovich picture Vasiliy Ermolovich · Dec 12, 2012

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 %>