Reputation: 3283
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?
Upvotes: 6
Views: 1783
Reputation: 2958
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
Upvotes: 0
Reputation: 8624
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,.
Upvotes: 7
Reputation: 1815
We can edit the multiple models like this..
<%= 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 %>
Upvotes: 0