art
art

Reputation: 105

How to edit model on show view of other model

I have the model Customer, and binded by has_many model Location. This is customer and his locations (adresses). After creating a new customer application redirects on show view of Customer model (shows all data just entered). On show view I have form for location add. There are already entered locations shows on this view and each of them has the link to edit each separate location. I need, when user click on location edit link, he redirects to show view of Customer model, but the form already contains the data of clicked location. Show view code of Customer model:

<p>Customer info:<br>
<strong><%= @customer.name %></strong><br />
<%= @customer.kind.name %><br />
<%= @customer.adres %><br />
<%= @customer.phone %><br />
<%= @customer.comment %><br />
</p>
<h3>Delivery location:</h3>

<% if @locations %>
<ul>
<% @locations.each do |loc| %>
  <li>
    <%= loc.adres %>
    <%= loc.phone %>
    <%= loc.comment %>
  </li>
<% end %>
</ul>
<% end %>

<%= form_for Location.new do |l| %>
  <%= l.text_field :adres %><br>
  <%= l.text_field :phone %><br>
  <%= l.text_field :comment %><br>
  <%= l.text_field :customer_id, type: "hidden", value: @customer.id %><br>
  <%= l.submit "Add" %>
<% end %>

<%= link_to "Home", root_path %>

Upvotes: 1

Views: 51

Answers (1)

Richard Peck
Richard Peck

Reputation: 76774

You'd just set @location depending on whether specific params have been sent:

#app/controllers/customers_controller.rb
class CustomersController < ApplicationController
   def show
      @customer = Customer.find params[:id]
      @location = params[:location_id] ? @customer.locations.find(params[:location_id]) : @customer.locations.new 
   end
end

This would allow you to populate the form as follows:

#app/views/customers/show.html.erb
Customer info:<br>
<%= content_tag :strong, @customer.name %>
<%= @customer.kind.name %>
<%= @customer.adres %>
<%= @customer.phone %>
<%= @customer.comment %>

<h3>Delivery location:</h3>
<% if @customer.locations %>
  <ul>
    <% @customer.locations.each do |loc| %>
      <%= content_tag :li do %>
        <%= loc.adres %>
        <%= loc.phone %>
        <%= loc.comment %>
        <%= link_to "Edit", customer_path(@customer, location_id: loc.id) %>
      <% end %>
    <% end %>
  </ul>
<% end %>

<%= form_for @location do |l| %>
  <%= l.text_field :adres %><br>
  <%= l.text_field :phone %><br>
  <%= l.text_field :comment %><br>
  <%= l.text_field :customer_id, type: "hidden", value: @customer.id %><br>
  <%= l.submit %>
<% end %>

--

To manage the routes (to pass location_id), you'll be best creating a custom route:

#config/routes.rb
resources :customers do
   get ":location_id", on: :member, action: :show, as: :location #-> url.com/customers/:id/:location_id
end

This will mean you'll have to reference the other link in your view:

<%= link_to "Edit", customer_location_path(@customer, loc.id) %>

Upvotes: 2

Related Questions