答案 0 :(得分:1)
在您的视图中添加局部视图,我建议创建一个视图/共享文件夹
app / views / shared / _flash.html.erb
<div id="flash-messages">
<% flash.each do |message_type, message| %>
<div class="alert text-center alert-<%= flash_class_name(message_type) %> alert-dismissable mb-0">
<span><%= message %></span>
<button type="button" class="close" data-dismiss="alert" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<% end %>
</div>
将此行添加到您的布局文件(在正文中)
app / views / application.html.erb
<%= render 'shared/flash' %>
现在在相关的动作视图文件中
app / views / [controller] / [create / update] .js.erb
$('#flash-messages').html("<%= j render 'shared/flash' %>");
并且您的控制器操作会像这样添加闪光灯
flash.now[:notice] = 'Request was saved successfully.'
答案 1 :(得分:0)
remote true会导致Rails使用ajax提交表单,因此您可以在前端处理请求
$(document).ready(() =>
function showFlash(message, color) {
// Handle finding your flash
// clear it, set color and message
}
$("#your_selector").on("ajax:success", function(event) {
const [data, status, xhr] = Array.from(event.detail);
showFlash(xhr.responseText, 'green');
}).on("ajax:error", function(event) {
showFlash('Sorry there was an error', 'green')
})
);
通过以上内容,您可以得到更多的幻想,但至少应该给您提供帮助。
https://guides.rubyonrails.org/working_with_javascript_in_rails.html