2013-01-11 21 views
0

叫我的應用程序我有一些代碼,一個控制器動作..顯示在軌道的提示信息,如果控制器從jQuery的

users_controller.rb

def my_method(age) 
    if age >18 
     flash[:notice]= "You are eligible." 
    else 
     flash[:notice]= "You are not eligible." 
    end 
    end 

我M利用jQuery的調用my_method ... (編碼是在提交的jQuery對話框按鈕)

jQuery.post('/users/my_method/', { age: jQuery('#age').val() }); 

但它不顯示Flash的消息,但在日誌中我見過的方法「my_method」被調用。告訴我如何顯示這些Flash消息?

回答

0

由於這是一個ajax請求,你將不得不通過json處理響應(通過rjs或其他)。

下面的代碼將舉一個例子(這是我的實際工作代碼之一)

例如:添加新朋友

#friends_controller.rb 
class FriendsController < ApplicationController 
    #<other methods> 
    def create 
    @friend = Friend.new(params[:friend]) 
    if @friend.save 
     flash.now[:success] = ["Friend request successfully sent"] 
     respond_to do |format| 
     format.js 
     end 
    else 
     render action: "new" 
    end 
    end 
end 

#view/friends/_form.html.erb 
<%= form_for @friend, :remote => true do |f| %> 
#code 
<% end %> 

#view/friend/create.js.erb 
$("#message_id").html("<%= escape_javascript raw(flash_display) %>"); 

note : flash_display is a helper method I used to display my messages 

#helpers/application_helper.rb 

def flash_display 
    response = "<div class='alert #{alert_class}'>" 
    response += "<button type='button' class='close' data-dismiss='alert'>x</button>" 
    flash.each do |name, msg| 
     msg.each do |m| 
     response = response + content_tag(:p, m) 
     end 
    end 
    response += "</div>" 
    flash.discard 
    response 
end 
+0

MESSAGE_ID將是佈局的控制器(股利或別的什麼)? –

+0

它的消息的div id顯示html :) – sameera207