有没有办法在rails控制器方法中提醒/弹出而不渲染任何其他js文件

时间:2015-12-18 09:09:03

标签: javascript ruby-on-rails ruby

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调用将进入这个方法,当条件来到其他时,我需要一个警告/弹出窗口说没有用户可以删除,然后我可以更新一些其他的事情。

提前致谢。

2 个答案:

答案 0 :(得分:6)

render html: "<script>alert('No users!')</script>".html_safe 块中尝试此操作:

<script>

请注意,如果您希望将<head>标记包含在正确的HTML布局中(带有render( html: "<script>alert('No users!')</script>".html_safe, layout: 'application' ) 标记等),则需要明确指定布局:

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

修改

这里有更多代码:

应用程序/控制器/ users_controller.rb:

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

user.rb:

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

配置/ routes.rb中:

{{1}}

答案 1 :(得分:0)

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

由于Rails是基于HTTP stateless protocol构建的,因此必须使用响应来满足每个请求。与TCPWeb Sockets不同,HTTP只能接收ad-hoc responses

  

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

这意味着您已将任何前端更改发送到浏览器,然后才能生效(IE,您只能说&#34;加载对话&#34 ;因为它不会被发送到浏览器):

#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响应