I have a Survey-Response application, where surveys can be created
with an arbitrary number of questions, and users can respond to an
arbitrary number of surveys.
A Survey has_many Questions and has_many Responses. Both a Question
and a Response has_many Answers. That way, everybody has a
relationship to everyone else.
In the Response#new for each Response.survey.questions I do a
@response.answers.build and set the questions_id attribute. That looks
like this:
1: survey = Survey.find(params[:survey_id])
2: @response = survey.responses.build
3: @response.survey.questions.each do |question|
4: @response.answers.build(:question_id => question.id)
5: end
All I want to do in the form template is get the Answer's Question's
text to display as a label. That looks like this:
Obviously Line 7 is junk, but that's basically what I want to do. How
do I get those prepopulated attribute values? I haven't been able to
find anything on this so it's either obviously staring me in the face
or an odd question.
I haven't had any responses in the past few days, so the problem must
be unsolvable in Rails. LOL
But let me rephrase the question more succinctly.
Assume, Shelf has a description and a set of items. Item has a
description, sku and color.
Given, I use build in my controller's new method to create a set of
models like this:
@shelf = Shelf.new
3.times { @shelf.items.build(:sku => GenerateNewSku, :color =>
'blue') }
Explain how to display the sku and color in the form for each item?
<% form_for @shelf do |f| %>
<%= f.label :description %>
<%= f.text_field :description %>
Why I want this: My app has Surveys, and each has many Questions. Each
Question has many Answers (one per user). The Answers also belong to a
Response, which belong to a User. Response can be thought of as the
user's answers to a Survey. If that's not clear, imagine a data
diagram in the shape of a diamond, with Survey at the top branching
down into Questions and Responses at the next level, and Answers at
the bottom. Each level is has_many with the one below it.
In the Response's form, I want to display Question.ask for each
question in the Survey as a label for each Answer in the Response.
Maybe there is a better way to go about doing this, but I've tried
numerous approaches, refactoring the databases, and am just about to
switch over to .NET (jk).
I don't think you're missing the point, and, yes, that's what *I*
think it should be too. The problem is "item" is type
ActionView:Helpers:FormBuilder, and therefore doesn't have a sku
property. Or maybe /I'm/ missing something
(I tried to make that clearer by naming it "item_fields" rather than
just "item" as you've done here.)
I don't think you're missing the point, and, yes, that's what *I*
think it should be too. The problem is "item" is type
ActionView:Helpers:FormBuilder, and therefore doesn't have a sku
property. Or maybe /I'm/ missing something
if you've got a form builder then form_builder.object is the object it
is bound to.