Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to render flash messages when remote true

I have a time logger controller method that calls from my view, called _embed_menu.html.erb

<%= link_to l(:start_time_logger) + ' #' + @issue.id.to_s + ' ',
   {:controller => '/time_loggers', :action => 'start', :issue_id => @issue.id},
    :class => 'icon icon-start',
    :"data-replace" => '#time-logger-menu',
    :remote => true
%>

The part of 'start' method, where I shown an error:

      respond_to do |format|
        format.js{ flash[:error] = l(:start_time_expired_error)}
      end

Now to the part of the rendering flash messages. application_helper.rb Have render_flash_messages function.

  def render_flash_messages
    s = ''
    flash.each do |k,v|
      s << content_tag('div', v.html_safe, :class => "flash #{k}", :id => "flash_#{k}")
    end
    s.html_safe
  end

and that function called on base.html.erb template.

<%= render_flash_messages %>

So the result - I launch a start method and flash shown only after I reload the page. I also tried to redirect with the hope that after this redirect the error will show.

redirect_to controller: 'issues', format: 'js'

but no result.

Maybe I can trigger re-rendering of <%= render_flash_messages %>?

like image 888
Rostislav Ruban Avatar asked Mar 24 '26 19:03

Rostislav Ruban


1 Answers

What happens when you click a remote: true link is that Rails creates a request for text/javascript and then runs the resulting javascript in that page.

Usually a js.erb template contains some javascript that modifies the document:

$("<%= escape_javascript(render @user) %>").appendTo("#users");

So if you want to alter the flash messages on the page you need to target the wrapping element and append it:

$("<%= escape_javascript(render_flash_messages) %>").appendTo("#flashes");

This assumes you have a wrapping element around the flash messages. Otherwise just add one to the layout.

<div id="flashes">
  <%= render_flash_messages %>
</div>
like image 74
max Avatar answered Mar 26 '26 13:03

max



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!