Question

Is it possible to pass the value of checked check_box_tags within a form_for in Rails inside a hash?

Here is a very generic, basic version of the form:

<%= form_for(:object, :url => { :action => 'create', :id => params[:id]}) do |f| %>
  <p>Field_a: <%= f.text_field(:field_a) %></p>
  <p>Field_b: <%= f.text_field(:field_b) %></p>
  <p>Field_c: <%= f.text_field(:field_c) %></p>
  <p>Check boxes:</p>
    <% check_box_choices_object_array.each do |s| %>
      <%= check_box_tag(s.name, 1, false) %>
      <%= .name %><br />
    <% end %>
    <%= submit_tag("Create") %>
<% end %>

Outputs roughly:

Field_a ___________________
Field_b ___________________
Field_c ___________________
Check boxes:
[] box_a
[] box_b
[] box_c
[] box_d
[] box_e
[] box_f
[] box_g

My problem is that since the available check boxes aren't actual fields in the object's table in the database (i.e. I'm not using check_box(:field) in the form), each checked check box gets passed as an individual parameter (i.e. "box_a" => "1", "box_b" => "1", "box_e" => "1"). I would like them to be passed as such:

:checked_boxes => {"box_a" => "1", "box_b" => "1", "box_e" => "1"}

This way, I can access them easily with params[:checked_boxes]. How do I do this, or, better yet, is there a better solution (I'm new to rails)?

Was it helpful?

Solution

I think you'd get the results you want if you wrap the checkboxes iterator in a fields_for :checked_boxes tag - or at least get you close to the results you want.

<%= form_for(:object, :url => { :action => 'create', :id => params[:id]}) do |f| %>
  <p>Field_a: <%= f.text_field(:field_a) %></p>
  <p>Field_b: <%= f.text_field(:field_b) %></p>
  <p>Field_c: <%= f.text_field(:field_c) %></p>
  <p>Check boxes:</p>
    <%= f.fields_for :checked_boxes do |cb| %>
      <% check_box_choices_object_array.each do |s| %>
        <%= cb.check_box(s.name, 1, false) %>
        <%= .name %><br />
      <% end %>
    <% end %>
  <%= submit_tag("Create") %>
<% end %>

OTHER TIPS

you can deal with no database attributes and models using attr_accessor

class Thing < ActiveRecord::Base
  attr_accessible :name
  attr_accessor :box_a, :box_b, :box_c
end

This way you can call these attributes in your form.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top