# Clean solution for a questionnaire

**URL:** <https://www.ruby-forum.com/t/clean-solution-for-a-questionnaire/168237>\
**Category:** Rails\
**Created:** [May 18, 2009, 4:51pm UTC](https://www.ruby-forum.com/t/clean-solution-for-a-questionnaire/168237 "2009-05-18T16:51:45Z")\
**Posts on this page:** 1\
**Page:** 1

<div class="post-metadata">

**Author:** ![brianj](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/b/54ee81/32.png) [@brianj](https://www.ruby-forum.com/u/brianj)\
**Post date:** [May 18, 2009, 4:51pm UTC](https://www.ruby-forum.com/t/clean-solution-for-a-questionnaire/168237/1 "2009-05-18T16:51:45Z")

</div>

The requirements:  
A user should be able to create, update and edit a questionnaire for  
others to complete.

The view should consist of a text\_field for each of the categories and  
under each category there should be 10 text\_fields for questions(the  
ones empty are to be ignored)

The models  
Questionnaire  
has\_many :categories  
has\_many :questions  
accepts\_nested\_attributes\_for :categories, :allow\_destroy =\> true  
accepts\_nested\_attributes\_for :questions, :allow\_destroy =\> true  
Category  
has\_many :questions  
belongs\_to :questionnaire

Question  
has\_many :answers  
belongs\_to :questionnaire  
belongs\_to :category

Controller

def new  
@questionnaire = Questionnaire.new  
@questionnaire.prepare\_categories #builds the different categories  
with default data  
10.times {@questionnaire.questions.build} #This seams to have no  
effect when I want to use fields\_for :questions in the view  
end

Questionnaire new view:

\<% form\_for @questionnaire do |f| %\>  
\<% @counter = 1 %\>  
\<% f.fields\_for :categories do |cat\_form|%\>  
topic: \<%= cat\_form.text\_field :topic %\>  
  
category text: \<%= cat\_form.text\_field :category\_text %\>  
  
\<% 10.times do %\>  
question text: \<%= text\_field\_tag “questionnaire  
[categories\_attributes][#{@counter}][questions\_text][]” %\>  
  
\<% end %\>  
\<% @counter += 1 %\>  
\<%end%\>  
\<%= f.submit %\>  
\<% end %\>

I could work with this solution but there are multiple problems with  
it:

1. Its ugly
2. When validations fail and the form is rerendered then I have to  
make another form to handle this.

My current workaround is to save the the questionnaire in the database  
in the new action and the categories to assign the questions with the  
categories by using the category\_ids as hidden fields, disgusting :-/

I was hoping I could build the categories and questions in memory in  
the above view and then use fields\_for for both questions and  
categories, I havent been able to make this work though.

I havent been able to find any help from googling on handling this  
issue.
