开发者

Creating multiple records in a nested form

I'm building a survey app and part of that app has two models:

#ResponseSet 
has_many :responses
accepts_nested_attributes_for :responses

#Response 
belongs_to :response_set
belongs_to :answer

As an example, you might have a survey with a multiple choice question where you can select multiple answers (What types of pets do you have? Dog, cat, horse).

What is supposed to happen is that when you submit your answers for a survey, a record is added to the Response table for each answer. So if you selected that you had a dog, cat and horse, 3 records would be added, each one referencing the Answer model via :answer_id.

I can d开发者_开发百科o it for questions with one answer, but ones with multiple answers is breaking my brain.

It gets more complicated because in a single survey there could be multiple questions each with multiple answers.

For reference, current form field names look like this:

response_set[responses_attributes][0][answer_id]
response_set[responses_attributes][1][answer_id]
response_set[responses_attributes][2][answer_id]

Generated by this:

<%= form_for @response_set, :url => complete_survey_path do |f| %>
  <%= f.fields_for :responses do |response| %>
    <%= response.check_box :answer_id %>
  <% end %>
<% end %>

So that'd be the field for answer_id in the response_attributes for 3 different questions.


The problem seems a little fuzzy to me without seeing the associations for Answer, the code for the create action, and the full generated HTML, but I believe this article by Shelly Roche provides a solution to your problem--perhaps with some refactoring to your model associations (i.e. ResponseSet has_many :responses, :through => :answers).

Unfortunately, the snippet she provides of her form.fields_for seems incomplete; the HAML ends with a break tag, but, in the HTML, the key bit (a hidden input field that ids the attribute associated with the check box) comes after a break tag.

Also, I can't say if the hidden fields containing the ids would be picked up automatically when saving the response, or if you would need to pull the fields out of params and process them manually.

But I'd wager that Shelly Roche would be willing to complete the snippets for you if you care to comment on her post.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜