I had a process where I wanted users to fill out a survey which had hierarchal categories AND be able to specify some additional data for specific capabilities that the user had.
Now, you could easily do this for a small subset and hand-code every item, but I wanted a flexible survey system that allowed true hierarchy and generalized code.
Let’s start off with the basic survey and capabilities models and relationships:
Your first attempt at making a survey map to many capabilities will be something like this (formtastic):
1
<%= f.input :capabilities, :as =>:check_boxes%>
But while that works on a basic level, it doesn’t work for capabilities that have a hierarchy and it doesn’t allow the user to specify additional data (i.e. answer a question about the capability).
So we’re going to need to accept nested resources. So we add this line to survey.rb:
Now we need to recursively display hierarchal capabilities (If you show videos on your site, you might allow the user to invoke it, or require the user to invoke it, but if you don’t show videos, we don’t care about your invocation restrictions):
First, let’s make a quick way to show/hide enable/disable elements within a div:
Keep in mind that we’re recursive, so first off, we’re passing in the collection of Capabilities we’re dealing with through the “collection” parameter, but that isn’t what we need to create in terms of nested form attributes–we need SurveyCapability objects for that, so we have to find or build them:
Then we create the fields_for section for nested form attributes and pass in the SurveyCapability we just created. Since we can specify that we want checkboxes here and specify the value, we make the checkbox the capability_id and make sure the ‘checked_value’ is the capability.id (it is ‘1’ by default).