Ajax flash message in ruby on rails

时光总嘲笑我的痴心妄想 提交于 2019-12-07 18:27:57

问题


I'm trying to show a flash message and render it with Ajax, but the message does not seem to be appearing until after I refresh the page.

Here's my create.rjs file:

page.insert_html :top, :feed_items, :partial => 'shared/feed_item', :object => @micropost
page.replace_html :user_info, pluralize(current_user.microposts.count, "micropost")
page[:micropost_form].reset
page.replace_html :notice, flash[:notice]
flash.discard

Here's the relevant part of my application layout view:

<div id= "notice"><% flash.each do |key, value| %>
   <div class="flash <%= key %>"><%= value %></div>
<% end %></div>

And here's the relevant part of my micropost controller:

class MicropostsController < ApplicationController
  before_filter :authenticate, :only => [:create, :destroy]
  before_filter :authorized_user, :only => :destroy

  def create
    @micropost  = current_user.microposts.build(params[:micropost])
    respond_to do |format|
      if @micropost.save
        flash[:success] = "Micropost created!"

        format.html { redirect_to root_path }
        format.js   
      else
        @feed_items = []
        render 'pages/home'
      end  
    end
  end

So why isn't the flash message showing up right away?


回答1:


Flash messages by design are stored in the session until the next page load. In the case of ajax, don't use flash. For one thing, the div to replace the message into may not exist, so you need to add that to your page as a container to add to. Second, just do it from a regular variable, not flash.

A regular variable would be:

@message = "Micropost created!"

instead of the flash[:success]

The js view would use this variable instead of flash.




回答2:


Instead of page.replace_html :notice, flash[:notice]
Try this page.replace_html :notice, "Some info to flash"



来源:https://stackoverflow.com/questions/5187965/ajax-flash-message-in-ruby-on-rails

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!