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

结束

在 Controller 中,我有此方法,将进行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

user.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

07-28 07:13