I got a task from my trainer. I want to edit two models in one form. For example, we have two entities student and address. In the new student part i want to add both student details and address. How can i achieve this through scaffolding in ruby on rails?
Asked
Active
Viewed 1,779 times
3 Answers
7
You can use accepts_nested_attributes_for and fields_for to build a form to create two model at same time, so you can edit them too. This kind of form called nested form
.
Here is a reference for you about Nested form,.

Thanh
- 8,219
- 5
- 33
- 56
0
We can edit the multiple models like this..
in students/edit.rhtml
Edit Student
<%= error_messages_for :student %>
<%= start_form_tag :action => 'update', :id => params[:id] %>
<p>
Student Name:
<%= text_field :student, :name %>
</p>
<h2>Address</h2>
<% for @address in @student.addresses %>
<%= error_messages_for :address %>
<% fields_for "address[]" do |f| %>
<p><%= f.text_field :name %></p>
<% end %>
<% end %>
<p><%= submit_tag 'Update' %></p>
<%= end_form_tag %>

vijikumar
- 1,805
- 12
- 16
0
I am not sure about scaffolding, but the expected behavior can be achieved by using form_tag instead of form_for.
<%= form_tag :url => , :html => {:id=> , :method => , :class => ""} do %>
<% text_field_tag <id>, <default_value>, :name=>"student[name]" %>
<% text_field_tag <id>, <default_value>, :name=>"student[age]" %>
<% text_field_tag <id>, <default_value>, :name=>"address[street]" %>
<% text_field_tag <id>, <default_value>, :name=>"address[city]" %>
<% text_field_tag <id>, <default_value>, :name=>"address[state]" %>
<% text_field_tag <id>, <default_value>, :name=>"address[country]" %>
<%= submit_tag 'save' %>
<% end %>
the params will then nicely be grouped in a hash like
{'student' => {'name' => , 'age' => }, 'address' => {'street' => , 'city' => . . .}}
which you can parse to update both the models

Ravi Sankar Raju
- 2,850
- 3
- 18
- 16