Every repository with this icon (
Every repository with this icon (
tree 871fcc8575bed8b98836956c91aa9cfa8d33dcea
parent 8759b6ba3f0928395fabf9559061e396c29310a6
| name | age | message | |
|---|---|---|---|
| |
.gitignore | ||
| |
README.markdown | ||
| |
Rakefile | ||
| |
app/ | ||
| |
config/ | ||
| |
db/ | ||
| |
doc/ | ||
| |
public/ | ||
| |
script/ | ||
| |
test/ |
accepts_nested_attributes_for Example
This app is based off an idea by acts_as_rubyist from #rubyonrails who was trying to get applicants to fill in questions and record their answers using accepts_nested_attributes_for.
Running The App
Download it, run rake gems:install and rake db:setup and launch the app.
Click on "New Applicant" and go through the process. Marvel.
Explanation
On the applicants/new.html.erb page you'll see the following code:
<% semantic_form_for @applicant, :html => { :method => :post } do |f| %>
<%= f.inputs %>
<% for question in @questions %>
<% f.fields_for :answers, Answer.new(:question => question) do |answer| %>
<p>
<%= question.text %><br>
<%= answer.text_field :text %>
<%= answer.hidden_field :question_id, :value => question.id %>
</p>
<% end %>
<% end %>
<%= f.submit %>
<% end %>
The semantic_form_for is from formtastic and allows me to just write the line right after it (f.inputs) which will provide a box containing all the fields for an applicant, only one at the moment.
The code immediately after this will iterate through all @questions, creating form elements for this. The beauty of fields_for here is that even though our Answer records are new, it'll still provide an index for them starting at 0. This means that the first answer form element will have the name of applicant[answers_attributes][0][text] and the next one will have applicant[answers_attributes][1][text]. Along with this we also have a hidden field for every answer representing the question it's going to link to.
When we press the submit button it goes off to ApplicantsController/create which calls Applicant.new(params[:applicant]), which will use the attributes passed in for the answers and using accepts_nested_attributes_for :answers in our Applicant model it will link them to this specific applicant, as well as the question we told it to link to.








