提问者:小点点

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


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时,我需要一个警报/弹出窗口说没有用户可以删除,然后我可以更新其他一些东西。

提前感谢。


共2个答案

匿名用户

在您的else块中尝试此操作:

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

请注意,如果您想包含

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

编辑:

这里有更多代码:

app/控制器/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
class User < ActiveRecord::Base
  # for the sake of example, simply have User.active return no users
  def self.active
    none
  end
end

配置/路由. 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在客户端-服务器计算模型中充当请求-响应协议。例如,网络浏览器可以是客户端,在托管网站的计算机上运行的应用程序可以是服务器。客户端向服务器提交HTTP请求消息。服务器向客户端返回响应消息,该响应包含有关请求的完成状态信息,并且还可以在其消息体中包含请求的内容。

这意味着您已经将任何前端更改交付给浏览器,然后它们才会生效(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 %>

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