Forum: Ruby on Rails Clean solution for a questionnaire

Announcement (2017-05-07): is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see and for other Rails- und Ruby-related community platforms.
Brian J. (Guest)
on 2009-05-18 18:51
(Received via mailing list)
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
 has_many :categories
 has_many :questions
 accepts_nested_attributes_for :categories, :allow_destroy => true
 accepts_nested_attributes_for :questions, :allow_destroy => true
 has_many :questions
 belongs_to :questionnaire

 has_many :answers
 belongs_to :questionnaire
 belongs_to :category


def new
    @questionnaire =
    @questionnaire.prepare_categories #builds the different categories
with default data
    10.times {} #This seams to have no
effect when I want to use fields_for :questions in the view

Questionnaire new view:

<% form_for @questionnaire do |f| %>
  <% @counter = 1 %>
  <% f.fields_for :categories do |cat_form|%>
    topic: <%= cat_form.text_field :topic %><br/>
    category text: <%= cat_form.text_field :category_text %><br/>
    <% 10.times do %>
        question text: <%= text_field_tag "questionnaire
[categories_attributes][#{@counter}][questions_text][]" %><br/>
    <% end %>
    <% @counter += 1 %>
  <%= f.submit %>
<% end %>

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

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
This topic is locked and can not be replied to.