我有一个简单的模型:
class Property < ApplicationRecord
belongs_to :user
has_many :invoices, dependent: :destroy
has_many :tenants, dependent: :destroy
validates :street, presence: true, length: { maximum: 50}
validates :city, presence: true, length: { maximum: 50}
validates :zip, presence: true, length: { maximum: 10}
validates :rent, presence: true, length: { maximum: 50}
def receivable
(self.rent.to_i + self.charges.to_i)
end
end
在控制台中尝试时,验证错误如期出现:
[2] pry(main)> prop = Property.new(street:"zzz")
=> #<Property:0x007fb99cde1cc0 id: nil, number: nil, streetype: nil, street:
"zzz", city: nil, zip: nil, rent: nil, charges: nil, user_id: nil, created_at:
nil, updated_at: nil>
[3] pry(main)> prop.save
(0.3ms) BEGIN
(0.8ms) ROLLBACK
=> false
[4] pry(main)> prop.errors.full_messages
=> ["User must exist", "City can't be blank", "Zip can't be blank", "Rent can't
be blank"]
这里是控制器:
def new
@user = current_user
@property = @user.properties.build
end
def create
@user = current_user
@property = @user.properties.create(property_params)
@property.user_id = current_user.id
if @property.save
flash[:notice] = "Nouveau Bien créé !"
redirect_to user_properties_path
else
redirect_to new_user_property_path
end
end
这是表单视图:
<div class="container center">
<div class="row white">
<div">
<h2>Nouveau bien</h2>
<%= simple_form_for([@user, @property]) do |j| %>
<%= j.input :number, label:"Numéro" %>
<%= j.input :streetype, label: "Laisser vide si nécessaire", collection: ["
","rue","boulevard","allée"] , prompt: "Choisir" %>
<%= j.input :street, label:"Nom" %>
<%= j.input :city, label:"Commune / Ville" %>
<%= j.input :zip, label:"Code Postal" %>
<%= j.input :rent, label:"Montant du Loyer" %>
<%= j.input :charges, label:"Montant des charges" %>
<br>
<%= j.submit 'Créer', class: "form-control btn btn-info" %>
<% end %>
</div>
</div>
</div>
故意省略其中一个字段时,控制器将重定向到正确的形式,但不显示验证错误消息。他们曾经露面,但由于某种原因而消失了。
知道为什么吗?
谢谢!
答案 0 :(得分:1)
您应该
而不是redirect_to new_user_property_path
块中的else
render 'new'
原因:redirect
指示浏览器发出新请求,因此您最终会因为错误而失去@property
对象的上下文。实际上,它对new
动作提出了新的要求。 render
将继续执行当前操作(在本例中为create
),并在new
视图中显示@property
,错误和以前的表单主体的响应。