控制器#create中的Rails呈现未加载页面



我有一份由公寓居民提交的表格,为访客申请通行证。

提交后,我已经设置了控制器以呈现模板或根据表单的输入将其重定向到另一个路径,并在单击提交按钮后在页面顶部显示一条闪光消息。

不知何故重定向工作正常,但渲染对页面没有任何作用。

尝试了带有渲染的flash.now,但没有flash,看起来它没有在页面上加载任何新内容。

class VisitorPassesController < ApplicationController
def new
@visitor_pass = VisitorPass.new
@controller = "visitor_passes"
end
def create
unless resident && correct_resident_key?
flash[:danger] = "Invalid resident key."
# render 'new'                     doesn't work 
# render action: 'new'             doesn't work
redirect_to new_visitor_pass_path  works
redirect_to '/visitor_passes/new'  works
return
end
.
.
. 
end 
end

下面是控制台的输出。

Rendering visitor_passes/new.html.erb within layouts/application
Rendered visitor_passes/new.html.erb within layouts/application
Rendered layouts/_rails_default.html.erb
Rendered layouts/_shim.html.erb
Resident Load (0.3ms)  SELECT "residents".* FROM "residents" WHERE "residents"."id" = ? LIMIT ?  [["id", 155], ["LIMIT", 1]] app/helpers/sessions_helper.rb:17:in 'current_user'
Rendered layouts/_header.html.erb (Duration: 3.1ms | Allocations: 760)
Completed 200 OK in 429ms (Views: 59.6ms | ActiveRecord: 2.3ms | Allocations: 33936)

Flash 消息显示在下一个响应周期(即重定向之后(。如果要显示 Flash 消息以响应当前请求,请使用 ActionDispatch::Flash::FlashHash#now。

class VisitorPassesController < ApplicationController
def new
@visitor_pass = VisitorPass.new
# just use the controller_name method provided by rails instead
end
def create
# ...
# prefer positive conditions instead of negative          
if resident && correct_resident_key?
# do something awesome
else
flash.now[:danger] = "Invalid resident key."
render :new
end
end
end

如果使用form_with,还要确保使用表单上的local: true选项,因为它默认为那些讨厌的 XHRremote: true请求。

相关内容

最新更新