我有一个Rails页面,允许用户选择一个或多个记录。
这是控制器动作:
def addinvtimes
@invoice = params[:invtimes][:invoice_id]
if params[:event_ids] != nil
params[:event_ids].each do |i|
newinvtime = Invtime.new(
linetype_id: 1,
invoice_id: @invoice,
event_id: i.to_i
)
if newinvtime.save
respond_to do |format|
if newinvtime.save
format.html { redirect_to invoice_path(@invoice), :notice => 'Invoice Item was successfully added.' }
else
format.html { redirect_to invoice_path(@invoice), :notice => 'ERROR.' }
end
end
end
end
end
end
我得到的错误是:
Render and/or redirect were called multiple times in this action
如何编码以不多次调用重定向?
答案 0 :(得分:2)
您的实际问题不在双重/重定向错误中,而是在逻辑中。假设params[:event_ids]
包含1000个项目。它应该被重定向到哪里?
params[:event_ids].each do |i|
if something.save
redirect_to .....
else
redirect_to .....
end
end
您可以在动作调用中仅重定向一次,但是您尝试在迭代器的each
步骤中调用重定向,我很确定您无法执行此操作。