表单提交后,从Rails控制器调用模态



我正在尝试在提交表单并创建客户后从控制器调用模态。我试着四处浏览,但没有找到答案。

这是我的控制器:

def create
@customer = Customer.new(packets_params)
respond_to do |format|
if @customer.save
UserMailer.with(customer: @customer).welcome_email.deliver

format.html { redirect_to(new_customer_path) }
else
format.html { render action: 'new' }
end
end
end

你能帮我吗,非常感谢。

如果您试图避免任何前端渲染,您可以返回一个JSON响应,其中包含您在erb文件中定义的模式的HTML:

def create
@customer = Customer.new(packets_params)
if @customer.save
UserMailer.with(customer: @customer).welcome_email.deliver
render(
modal: render_to_string('welcome_modal.html.erb'),
status: :created
)
else
render(
errors: @customer.errors
status: :bad_request
)
end
end
end

然后你的模式模板可能看起来像:

# app/views/mycontroller/_welcome_modal.html.erb
<div class="modal welcome-modal" tabindex="-1" data-backdrop="static" role="dialog">
<h1> Welcome! </h1>
</div>

确保模板文件位于视图所需的标准目录结构中,并以_为前缀表示它是分部文件。

在前端,您可以将请求作为AJAX调用,并将模态呈现到屏幕上或处理返回的错误:

// some JS file - implementation is proof of concept and not clean
$('form').on('submit', function () {
var data = $('form').serialize();
$.post('/customer', data)
.done(function (res) { /* render modal */ }
.error(function (error) { /* handle errors */ }
});

最新更新