38

在http://guides.rubyonrails.org/layouts_and_rendering.html上名为 'Layouts and Rendering in Rails' 的 Ruby On Rails 指南中使用 :alert (或 :notice)和 render 方法对我不起作用

这是指南中提供的示例代码:

    def index
      @books = Book.all
    end

    def show
      @book = Book.find_by_id(params[:id])
      if @book.nil?
        @books = Book.all
        render "index", :alert => 'Your book was not found!'
      end
    end

我有一个看起来像这样的 hello 控制器:

    class HelloController < ApplicationController
      def index
        @counter = 5
      end
      def bye
        @counter = 4
        render "index", :alert => 'Alert message!'
      end
    end

我的 index.html.erb 视图如下所示:

    <ul>
    <% @counter.times do |i| %>
      <li><%= i %></li>
    <% end %>
    </ul>

访问时http://localhost:3000/hello/bye,我看到索引视图,即按预期显示从 1 到 4 的数字列表,但没有“警报消息!” 警报显示。

我的布局使用它来显示警报消息:

    <% flash.each do |k, v| %>
      <div id="<%= k %>"><%= v %></div>
    <% end %>
4

3 回答 3

31

我对 Rails 指南为什么提到在 中使用 flash 值感到困惑render,因为它们目前似乎只在redirect_to其中起作用。flash.now[:alert] = 'Alert message!'如果您在渲染方法调用之前放置一个,我认为您会发现您的方法有效。

编辑:这是将修复的指南中的缺陷,您应该在调用渲染之前使用单独的方法调用来设置闪光灯。

于 2013-03-03T21:00:42.210 回答
29

尝试

  def bye
    @counter  = 4
    flash.now[:error] = "Your book was not found"
    render :index
  end
于 2013-03-03T20:59:46.120 回答
9

通常你会做这样的事情:

if @user.save
  redirect_to users_path, :notice => "User saved"
else
  flash[:alert] = "You haz errors!"
  render :action => :new
end

你想要做的是(我更喜欢这种语法):

if @user.save
  redirect_to users_path, :notice => "User saved"
else
  render :action => :new, :alert => "You haz errors!"
end

...但是,这对ActionController::Flash#render.

但是,您可以扩展ActionController::Flash#render完全按照您的意愿行事:

config/initializers/flash_renderer.rb使用以下内容创建:

module ActionController
  module Flash

    def render(*args)
      options = args.last.is_a?(Hash) ? args.last : {}

      if alert = options.delete(:alert)
        flash[:alert] = alert
      end

      if notice = options.delete(:notice)
        flash[:notice] = notice
      end

      if other = options.delete(:flash)
        flash.update(other)
      end

      super(*args)
    end

  end
end

参考:http ://www.perfectline.co/blog/2011/11/adding-flash-message-capability-to-your-render-calls-in-rails-3/

于 2015-09-01T22:06:02.040 回答