有没有办法在不渲染任何其他 js 文件的情况下在 rails 控制器方法中发出警报/弹出窗口

Is there a way to alert/popup in a rails controller method without rendering any other js file

本文关键字:方法 控制器 窗口 rails 任何 有没有 文件 js 其他 情况下      更新时间:2023-09-26
def delete_users
  users = User.active.where(:id=>params[:users])
  users.each do |user|
    array = []
    if user.active?
      array << user
    end
  end
  if (array.count > 0)
    user.update_attributes(:status => "inactive")
  else
    "I want an alert/popup here saying no users, when 'delete_users' is called and the condition comes here."
    ........ do other stuff ......
  end  
end  

结束

在控制器中,我有这种方法,将进行 ajax 调用以使用此方法,当条件出现时,我需要一条警报/弹出窗口,说没有用户可以删除,然后我可以更新一些其他东西。

提前谢谢。

在你的else块中试试这个:

render html: "<script>alert('No users!')</script>".html_safe

请注意,如果要在适当的 HTML 布局中包含 <script> 标记(带有 <head> 标记等(,则需要显式指定布局:

render(
  html: "<script>alert('No users!')</script>".html_safe,
  layout: 'application'
)

编辑:

下面是更多代码:

app/controllers/users_controller.rb:

class UsersController < ApplicationController
  def delete_users
    users = User.active.where(:id=>params[:users])
    array = []
    users.each do |user|
      if user.active?
        array << user
      end
    end
    if (array.count > 0)
      user.update_attributes(:status => "inactive")
    else
      render(
        html: "<script>alert('No users!')</script>".html_safe,
        layout: 'application'
      )
    end
  end
end

用户.rb:

class User < ActiveRecord::Base
  # for the sake of example, simply have User.active return no users
  def self.active
    none
  end
end

config/routes.rb:

Rails.application.routes.draw do
  # simply visit localhost:3000 to hit this action
  root 'users#delete_users'
end

您不能直接从控制器调用对话框/弹出框;它必须构成对浏览器的响应的一部分。


因为 Rails 建立在 HTTP 无状态协议之上,所以每个请求都必须得到一个响应。与TCPWeb Sockets不同,HTTP只有接收临时响应的能力:

HTTP 在客户端-服务器计算模型中充当请求-响应协议。例如,Web 浏览器可能是客户端,在托管网站的计算机上运行的应用程序可能是服务器。客户端向服务器提交 HTTP 请求消息。提供 HTML 文件和其他内容等资源或代表客户端执行其他功能的服务器向客户端返回响应消息。响应包含有关请求的完成状态信息,并且还可能在其消息正文中包含请求的内容。

这意味着您已经在浏览器生效之前将任何前端更改交付给浏览器(IE 你不能只说"加载对话框",因为它不会发送到浏览器(:

#app/controllers/your_controller.rb
class YourController < ApplicationController
   respond_to :js, only: :destroy_users #-> this will invoke destroy_users.js.erb
   def destroy_users
      @users = User.active.where(id: params[:users]).count
      if @users.count > 0
         @users.update_all(status: "inactive")
      else
         @message = "No users......"
      end
   end
end
#app/views/your_controller/destroy_users.js.erb
<% if @message %>
  alert(<%=j @message %>);
<% end %>

上面的代码调用了可以使用respond_to调用的js.erb响应