Render the Flash message through js.erb file

2019-04-16 14:36发布

In my Rails app, I want to render the flash message from my controller method delete_option (questions_controller) to a partial _edit.html.erb inside questions folder itself. I have a js file delete_option.js.erb and I could successfully render the edit using the below line to a div element with id edit_subquestion.

$("#edit_subquestion").html("<%= escape_javascript(render(:partial => "edit")) %>");

I put a div element inside the _edit.html.erb to render the flash message as given below.

<div id="flash_delete_option"></div>

I am trying to render the flash message from the method delete_option to the above div element as given below.

if((<%=flash[:success]%>).length > 0)
    $("#flash_delete_option").html("<%= escape_javascript(render('<%=flash[:success]%>')) %>");

I am getting syntax errors. Please help to resolve this. Everything tried as per the answer. Not getting it.

2条回答
一纸荒年 Trace。
2楼-- · 2019-04-16 15:24

Jesse Wolgamott : if loop was the problem. I modified it. now, its working.

<% unless flash[:success].blank? %>
    $("div .success").html("<%= escape_javascript (raw(flash[:success])) %>");
    $("div .success").show(200);
    $("div .success").click(function(){
        $("div .success").hide(200);
    });
<% end %>
查看更多
爷、活的狠高调
3楼-- · 2019-04-16 15:33

You can use ruby to do conditionals in your edit.js.erb file. Also, since you're inside the escape_javascript, you don't call render in there.

<% if flash[:success] %>
    $("#flash_delete_option").html("<%= escape_javascript flash[:success]%>");
<% end %>
查看更多
登录 后发表回答