I am trying to convert an HTML survey into a Rails app, but have encountered difficulties when attempting to carry over the functionality of checkboxes. Briefly, the problem is that checking the the checkboxes and then submitting the survey saves nothing in the database.
My model:
class Survey < ActiveRecord::Base
partial_updates = false
include ActiveModel::Serialization
serialize :checkbox_question, Hash
end
My controller:
class SurveysController < ApplicationController
def new
@survey = Survey.new
end
def create
@survey = Survey.new(survey_params)
respond_to do |format|
if @survey.save
format.html { redirect_to @survey, notice: 'Survey was successfully created.' }
format.json { render :show, status: :created, location: @survey }
else
format.html { render :new }
format.json { render json: @survey.errors, status: :unprocessable_entity }
end
end
end
private
def survey_params
params.require(:survey).permit(:question_one, :question_two, . . ., {:checkbox_question => {}})
end
end
Creating survey attributes for each of the checkbox would be possible, but it would drastically increase the size of my model and database. I don't want to take this approach if I can avoid it.
Here is the HTML for the new survey view:
. . .
<%= f.fields_for :checkbox_question, @survey.checkbox_question |p| %>
<%= p.check_box :option_one %><label>Option 1</label>
<%= p.check_box :option_two %><label>Option 2</label>
<%= p.check_box :option_three %><label>Option 3</label>
<% end %>
. . .
<div class="submit step" id="complete">
<i class="icon-check"></i>
<%= f.submit "Submit" %>
</div>
When I create a new survey, use the checkboxes, and then submit it, the checkbox values are not saved in the relevant attributes—though all of the other fields save correctly. Moreover, if I insert “raise survey_params.insert” at the top of the Create action in my controller, then submit a new survey, request parameters includes the checkbox values as being checked. For example, if I check boxes 1 and 3 in the first checkbox section it returns:
{"utf8"=>"✓", "authenticity_token"=>"0tmM1/CXRY9XYA/3tdzBZ6frTom8EGZvaYlq3EEE6vc=", "survey"=>{"question_one"=>"answer 1", "question_two"=>"answer 2", . . . "checkbox_question"=>{"option_one"=>"1", "option_two"=>"0", "option_three"=>"1"} . . . .}
So, the Rails form that I am using appears to be working. It just seems unable to save.
I have attempted the fixes to similar-sounding problems described here (http://archives.ryandaigle.com/articles/2008/4/1/what-s-new-in-edge-rails-partial-updates), here (Using Rails serialize to save hash to database), and here (https://github.com/rails/strong_parameters/issues/83), all with no luck.
Any suggestions would be appreciated. Thank you!