JavierQQ23
JavierQQ23

Reputation: 714

Rails - Use the same form with new/edit using fields_for

I have 5 models,

  1. Person
  2. person_car
  3. car (has many tires)
  4. person_car_tire
  5. tire (belongs to car)

so I have this view _form.html.erb

<%= form_for(@person) do |f| %>
  <div class="field">
    <%= f.label :name %><br />
    <%= f.text_field :name %>
  </div>
  <div>

  <% Car.all.each do |c|%>
  <div class="field">
    <%= f.fields_for(:person_cars) do |ff|%>
      Car Name:   <%= ff.check_box :car_id %>|<%= c.car_name%>
      <% c.tires.each do |b|%>
      <div class="field">
        <%= ff.fields_for(:person_car_tires) do |fff|%>
          Tire: <%#= fff.check_box :tire_id%>|<%= b.tire_name%>
        <%end%>
      </div>
      <%end%>
    <%end%>
  </div>

  <div class="actions">
    <%= f.submit %>
  </div>
<% end %>

And when I save it works perfectly, the problem comes when I want to edit using this form because it duplicates data of each car 4 times in the view. I've been searching and fields for allows extra options so I made:

<%= form_for(@person) do |f| %>

  <div class="field">
    <%= f.label :name %><br />
    <%= f.text_field :name %>
  </div>
  <div>

  <% @person.cars.each do |c|%>
  <div class="field">
    <%= f.fields_for(:person_cars, c) do |ff|%>
      Actividad:   <%= ff.check_box :car_id %> | <%= c.car.name%>
      <% c.person_car_tires.each do |t|%>
      <div class="field">
        <%= ff.fields_for(:person_car_tires, t) do |fff|%>
          Tarea: <%#= fff.check_box :tire_id%>|<%#= t.tire.name%>
        <%end%>
      </div>
      <%end%>
    <%end%>
  </div>
  <%end%>

  <div class="actions">
    <%= f.submit %>
  </div>
<% end %>

and it now works, but only show the cars and tires that I've selected on the new action. not all as I wanted (because if I use the first form it duplicates checkboxes in the view).

How can I use the same form for both actions?

Hope someone can help me.

Upvotes: 0

Views: 1874

Answers (1)

Salil
Salil

Reputation: 9722

You can use the same _form partial for both new and edit. You just need to pass local variables set to different values to this form. Basically, whatever differs, abstract it away as a parameter (local variable) to this function-like partial.

Upvotes: 0

Related Questions