2015-12-18 13 views
2
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 

有沒有一種方法,以提醒在軌控制方法/彈出勿使任何其他js文件

在控制器,我有這樣的方法,Ajax調用會進行去這個方法當條件變成其他的時候,我需要一個警告/彈出窗口說沒有用戶可以刪除,然後我可以更新其他的東西。

在此先感謝。

+0

放於別的塊來調用'返回渲染:文本=>「沒有用戶在那裏刪除」' –

回答

5

else塊試試這個:

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

注意,如果你想在一個適當的HTML佈局(與<head>標籤等)<script>標籤,你需要明確指定佈局:

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

編輯:

這裏有一個小更多的代碼:

應用程序/控制器/ 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 
+0

嘗試,但沒」工作。我認爲它應該呈現回模板才能正常工作。 – Sravan

+0

什麼不行?這對我有用。我在答案中添加了一些額外的代碼。 –

0

不能調用對話/彈出框直接從控制器;它必須形成響應到您的瀏覽器的一部分。


由於Rails是建立在HTTP stateless protocol,每個請求必須用響應得到滿足。不像TCPWeb Sockets,HTTP僅具有接收ad-hoc responses容量:

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 %> 

上面的代碼調用js.erb響應其可以使用respond_to

+0

我們甚至不能在控制器中間顯示Flash消息Action? – Sravan

+0

絕對不是。您必須將響應發送回服務器 –

相關問題