2011-04-19 40 views
2

我的控制器創建功能如何在使用Ajax和JQuery的Rails 3中顯示Flash錯誤消息?

def create 
    @group = Group.new(params[:group]) 
    @group.company=current_user.company 
    respond_to do |format| 
    if @group.save 
     format.html { redirect_to(@group, :notice => 'Group was successfully created.') } 
     format.js 
    else 
     flash.now[:error][email protected]_messages 
     format.html { render :nothing => true } 
     format.js 
    end 
    end 
end 

create.js.erb文件

$('<%= escape_javascript(render(:partial => @group))%>').appendTo('#groups'); 
$("#new_group")[0].reset(); 
+0

請將您的代碼放在代碼標籤({}符號) – ipsum 2011-04-19 13:40:55

回答

2

爲Flash創建一個div當頁面最初加載:

<div class="flash-error"></div> 

設置一個javascript js.erb文件中的閃存變量。然後檢查一個值並使用javascript更新「flash-error」div。它可能會是這個樣子:

$('<%= escape_javascript(render(:partial => @group))%>').appendTo('#groups'); 
$("#new_group")[0].reset(); 
var flashError = "<%=flash.now[:error]%>"; 
if (flashError){ 
    $(".flash-error").html(flashError); 
} 
10

這是我解決這個問題.... 我把這些在我所有的js.erb文件

$('#flash').html("<%= escape_javascript raw(flash_display) %>"); 

有了這個助手

def flash_display 
    response = "" 
    flash.each do |name, msg| 
    response = response + content_tag(:div, msg, :id => "flash_#{name}") 
    end 
    flash.discard 
    response 
end 

這適用於已經在佈局中設置的flash div

<div id="flash"> 
    <% flash.each do |name, msg| %> 
    <%= content_tag :div, msg, :id => "flash_#{name}" %> 
    <% end %> 
</div> 

希望這會有幫助

+0

對我來說非常合適,非常感謝 – sameera207 2012-11-26 08:18:35

相關問題