我正在学习 RoR,但我找不到以相同形式验证我的模型的方法。它正在验证,但它只显示一个模型(地址)的错误消息,并且它正在填充另一个模型的其他输入字段,就像在进行更改之前一样。我尝试了几件事,但都没有奏效。
在 edit.html.erb 中,我显示了错误消息。仅当一个模型不正确时,此方法才能正常工作。如果两个模型中的输入都不正确,我只会看到地址的错误消息,并且相互性的输入字段被重置为以前的值。
我认为这就是你真正需要的。我的地址控制器是空的。除验证外,其他一切工作正常。
马蒂亚斯。
编辑.html.erb:
<h1>Edit Mutuality</h1>
<%= form_for @mutuality do |f| %>
<%= fields_for @address do |fa| %>
<% if @mutuality.errors.any? %>
<h2>Errors:</h2>
<ul>
<% @mutuality.errors.full_messages.each do |msg| %>
<li><%= msg %></li>
<% end %>
</ul>
<% end %>
<% if @address.errors.any? %>
<h2>Errors:</h2>
<ul>
<% @address.errors.full_messages.each do |msg| %>
<li><%= msg %></li>
<% end %>
</ul>
<% end %>
<table>
<tr>
<td>
<%= f.label :name %>
</td>
<td>
<%= f.text_field :name %>
</td>
</tr>
<tr>
<td>
<%= f.label :phone %>
</td>
<td>
<%= f.text_field :phone %>
</td>
</tr>
<tr>
<td>
<%= f.label :contact %>
</td>
<td>
<%= f.text_field :contact %>
</td>
</tr>
<tr>
<td>
<%= fa.label :street %>
</td>
<td>
<%= fa.text_field :street %>
</td>
</tr>
<tr>
<td>
<%= fa.label :number %>
</td>
<td>
<%= fa.text_field :number %>
</td>
</tr>
<tr>
<td>
<%= fa.label :zipcode %>
</td>
<td>
<%= fa.text_field :zipcode %>
</td>
</tr>
<tr>
<td>
<%= fa.label :city %>
</td>
<td>
<%= fa.text_field :city %>
</td>
</tr>
<tr>
<td>
</td>
<td>
<%= f.submit %>
</td>
</tr>
</table>
<% end %>
控制器:
class MutualitiesController < ApplicationController
def index
@mutualities = Mutuality.all
end
def show
@mutuality = Mutuality.find(params[:id])
end
def new
@mutuality = Mutuality.new
@address = Address.new
end
def create
@mutuality = Mutuality.new(params[:mutuality])
@address = Address.new(params[:address])
if @address.save
@mutuality.address_id = @address.id
if @mutuality.save
redirect_to mutualities_path, :notice => "Mutuality saved with succes!"
else
render "new"
end
else
render "new"
end
end
def edit
@mutuality = Mutuality.find(params[:id])
@address = Address.find(@mutuality.address_id)
end
def update
@mutuality = Mutuality.find(params[:id])
@address = Address.find(@mutuality.address_id)
if @address.update_attributes(params[:address])
if @mutuality.update_attributes(params[:mutuality])
redirect_to mutualities_path, :notice => "Mutuality updated with succes!"
else
render "edit"
end
else
render "edit"
end
end
def destroy
@mutuality = Mutuality.find(params[:id])
@address = Address.find(@mutuality.address_id)
@mutuality.destroy
@address.destroy
redirect_to mutualities_path
end
end