I’m trying to build a form, but haven’t quite got it sorted. Here’s
the background:
There are form_templates (e.g. questionnaires) and related questions.
The form_template model basically contains header information and acts
as a parent to the questions. There is an arbitrary number of
questions on a form_template. We want to be able to administer a
form_template many times and change the questions over time, etc. So,
there is a form_actuals table that holds the header information for an
instance of a “real” form_template, and there is a form_data table
that holds the answers to the questions for a given form_actual filled
out by a person. A form_template can have many form_actuals; likewise
a question can have many form_data.
So,
Definitions: form_templates --< questions
Instances: form_actuals --< form_data
To get the information into the database I want to be able to set up
the definitions (form_templates and questions) and then enter the
actual responses (form_actuals and form_data).
The view (simplified):
1 <% form_for :form_actual, :url => { :action => :create } do |
form| %>
2
3
<%= @question.question_number.to_s %> | <%=h @question.question %> | <%= f.text_field(“answer”) %> |
18
19 <% end %>
The form_actuals controller:
def create
@form_actual = FormActual.new(params[:form_actual])
params[:form_data].each_value { |form_data|
@form_actual.form_data.build(form_data) }
If the ‘Save’ button is clicked.
if params[:save_button] && @form_actual.save
etc…
end
So, I start by iterating through the questions (line 4) and then
creating fields for form_data (line 5) based on them. I’m passing the
id and text of a question to a form_data record (lines 6 and 7) so
that they are stored on a form_data record (if a question is modified,
it should not affect previously entered form_data). Then I display the
question number and text on the form (lines 10 and 11) and set up a
field for the user to enter the answer (line 12).
The catch is this: “answer” is the column in form_data that stores an
actual response to a question, but I get an “undefined method `answer’
for #Question:0x354feb8” error unless I add a dummy column “answer”
to the questions table. If there is a column called “answer” in
questions, then the form is created successfully and correctly (with
indexed fields) and once it is submitted the controller does its magic
to parse the form into separate records in form_data.
This seems odd and I’m wondering if I have something fundamentally
wrong here. Thanks for any insight, and apologies for the length of
this post.