[英]Rails: model validations and errors not appearing
我正在從一種形式創建多個對象:
def new
@opening_hour = []
7.times do
@opening_hour << OpeningHour.new
end
render :template => "stores/opening_hours/new"
end
def create
params["opening_hour = "].each do |hour|
if hour["day"] != "" || hour["closes"] != "" || hour["opens"] != ""
@res = OpeningHour.new(opening_hour_params(hour))
puts @res.errors unless @res.save
redirect_to(store_items_index_path)
return
end
end
end
表單看起來像這樣:
<%= form_tag store_opening_hours_create_path do %>
<% @opening_hour.each do |hour| %>
<%= fields_for 'opening_hour = []', hour do |p|%>
<% if @res.errors.any? %>
<div class="centerList">
<div id="error_explanation">
<h2><%= pluralize(@res.errors.count, "error") %> <%= t 'store_edit_account_errors' %></h2>
<% @res.errors.full_messages.each do |message| %>
<li><%= message %></li>
<% end %>
</div>
</div>
<% end %>
但是,在我單擊提交之后,我得到一個錯誤: undefined method 'errors' for nil:NilClass
在此行<% if @res.errors.any? %>
<% if @res.errors.any? %>
。 如果我從表單中刪除錯誤部分,則一切正常,並創建了所有7個對象。 據我了解,這是因為@res的值為nil而發生的...但是不確定如何使它工作...有什么想法嗎?
更新1
def new
@opening_hour = []
7.times do
@opening_hour << OpeningHour.new
end
render :template => "stores/opening_hours/new"
end
def create
params["opening_hour = "].each do |hour|
if hour["day"] != "" || hour["closes"] != "" || hour["opens"] != ""
@res = OpeningHour.new(opening_hour_params(hour))
if @res.success
format.html { redirect_to @res, notice: 'Hours were successfully created.' }
format.json { render :show, status: :ok, location: @res }
else
format.html { render :'stores/opening_hours/edit' }
format.json { render json: @res.errors, status: :unprocessable_entity }
end
end
end
end
嘗試在create
操作的頂部實例化它。 可能沒有像您想象的那樣設置。
def create
@res = OpeningHour.new
# ...
end
您還應該在new
操作中執行類似的操作,也未在其中設置@res
。
如果您重定向,則會觸發一個新請求,該請求不會保留內存中之前發生的所有事情。
這就是為什么:
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.