Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails simple_form checkboxes for serialized Array field

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.

like image 322
Joerg Avatar asked Dec 12 '12 06:12

Joerg


2 Answers

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 %>
like image 121
Vasiliy Ermolovich Avatar answered Nov 08 '22 21:11

Vasiliy Ermolovich


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
  }
%>
like image 5
Brian Davis Avatar answered Nov 08 '22 22:11

Brian Davis