1

我的应用程序中的 Flash 消息存在问题。实际上,在我的应用程序中,我使用了用于用户身份验证的设计,并且我的应用程序使用了 ruby​​ 1.9.3 和 rails 3.2.2。

当用户登录、注销并注册新帐户时,设备 flash[:notice] 工作正常。

在 Rails 中 flash[:notice] 和 flash[:alert] 是默认的 flash 消息。

刷新消息仅在页面重新加载或用户从一页到另一页否定时显示一次

问题是当用户登录时,设备 flash[:notice] 正在显示,但是当我重新加载页面时 flash[:notice] 正在显示,但在 rails 中 flash[:notice] 只会显示一次

实际上问题是当我尝试创建一个新帖子时,我已经重定向到显示页面,并且我已经为 flash 消息编写了辅助方法,我从应用程序布局中调用了这个方法来显示 flash 消息。

在控制器创建方法中

def create
  @asset = Asset.new(params[:asset])
  @asset.user_id = current_user.id

  respond_to do |format|
    if @asset.save
      format.html { redirect_to @asset, alert: 'Asset was successfully created.' }
      format.json { render json: @asset, status: :created, location: @asset }
    else
      format.html { render action: "new" }
      format.json { render json: @asset.errors, status: :unprocessable_entity }
    end
  end     
end

显示 flash 消息的 Helper 方法

FLASH_TYPES = [:error, :warning, :success, :message,:notice,:alert]

def display_flash(type = nil)
  html = ""  
  if type.nil?
    FLASH_TYPES.each { |name| html << display_flash(name) }
  else
    return flash[type].blank? ? "" : "<div class=\"#{type}\"><p>#{flash[type]}</p>     </div>"
  end
  html.html_safe
end

我已经从应用程序布局中调用了这个方法

= display_flash

我尝试过使用 flash[:alert]、flash[:error]、flash[:message] 但视图页面上没有消息显示,我尝试过使用名为 flash_message 的 gem,这也只显示 flash[:notice]

请帮我解决这个问题

4

1 回答 1

-1

嗨,我正在使用这种方法来显示 Flash 消息。首先我做部分

shared中的_flash.html.erb。这个部分的代码

 <% [:alert, :notice, :error].select { |type| !flash[type].blank? }.each do |type| %>
<p>
  <% if flash[:notice] %>
    <div class="alert-message error">
      <h2 style="color: #ffffff;">Notice:</h2> <br/>
      <%= flash[type] %>
    </div>
<% elsif flash[:error] %>
    <div class="alert-message error">
      <h2 style="color: #ffffff;">Errors</h2> <br/>
      <% flash[:error].each_with_index do |error, index| %>
          <%= index+1 %>. <%= error %> <br/>
      <% end %>
    </div>
  <% end %>


   </p>
  <% end %>

我在这样的应用程序布局中调用它

  <div id="flash">
    <%= render :partial => 'shared/flash', :object => flash %>
  </div>

并且在控制器使用通知中,像这样发出警报

  flash[:notice] = 'Admin was successfully created.'
  flash[:alert] = 'Admin was successfully created.'

但是为了显示错误,我使用数组,因为它可能不止一个。像这样

       def create
         @user = User.new(params[:user])
         @user.is_activated = true
# @user.skip_confirmation!
if @user.save
  role = Role.find_by_name("admin")
  RoleUser.create!(:user => @user, :role => role)
  redirect_to :controller => '/administrator', :action => 'new'
  flash[:notice] = 'Admin was successfully created.'
else
  flash[:error]=[]
  @user.errors.full_messages.each do |error|
    flash[:error] << error
  end

  render :action => "new"
end

结尾

在 application.js 中添加这一行

   setTimeout("$('#flash').html(' ');", 10000);

使用它并享受!!!!!!!!!!!!!!!!

于 2012-04-10T11:55:19.877 回答