我正在从单一表单创建多个对象:
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? %>
。如果我从表单中删除错误部分,那么一切正常,并创建所有7个对象。根据我的理解,这种情况正在发生,因为价值@res是零...但不确定如何使这项工作......任何想法?
更新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
答案 0 :(得分:0)
尝试在create
操作的顶部实例化它。可能它并没有像你想象的那样得到设定。
def create
@res = OpeningHour.new
# ...
end
您还必须在new
操作中执行类似的操作,@res
也未设置此处。
答案 1 :(得分:0)
如果您重定向,则会触发一个新请求,其中内存中发生的所有事情都不会保留。
这就是为什么: