我有模型self.context['request']
,并由Customer
模型has_many
绑定。这是客户和他的位置(地址)。创建新客户应用程序后,在Location
模型的show
视图上重定向(显示刚刚输入的所有数据)。在Customer
视图中,我有用于位置添加的表单。此视图上已显示已输入的位置,每个位置都有编辑每个单独位置的链接。我需要,当用户点击位置编辑链接时,他会重定向到show
模型的show
视图,但该表单已包含点击位置的数据。 Customer
Show
模型的Customer
视图代码:
<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 %>
答案 0 :(得分:2)
您只需设置@location
,具体取决于是否已发送特定参数:
#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
这将允许您按如下方式填充表单:
#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 %>
-
要管理routes
(传递location_id
),您最好创建自定义路线:
#config/routes.rb
resources :customers do
get ":location_id", on: :member, action: :show, as: :location #-> url.com/customers/:id/:location_id
end
这意味着您必须引用视图中的其他链接:
<%= link_to "Edit", customer_location_path(@customer, loc.id) %>