在Ruby On Rails指南中使用:alert(或:notice)和render方法,称为"Rails中的布局和渲染",对我来说不起作用:

Car*_*app 31 ruby-on-rails ruby-on-rails-3.2

http://guides.rubyonrails.org/layouts_and_rendering.html上使用来自Ruby On Rails指南(称为"Rails中的布局和渲染")的render方法使用:alert(或:notice)对我来说不起作用

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

    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
Run Code Online (Sandbox Code Playgroud)

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

    class HelloController < ApplicationController
      def index
        @counter = 5
      end
      def bye
        @counter = 4
        render "index", :alert => 'Alert message!'
      end
    end
Run Code Online (Sandbox Code Playgroud)

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

    <ul>
    <% @counter.times do |i| %>
      <li><%= i %></li>
    <% end %>
    </ul>
Run Code Online (Sandbox Code Playgroud)

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

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

    <% flash.each do |k, v| %>
      <div id="<%= k %>"><%= v %></div>
    <% end %>
Run Code Online (Sandbox Code Playgroud)

Dan*_*ich 27

我很困惑为什么Rails指南提到使用flash值render,因为它们现在似乎只能工作redirect_to.如果你flash.now[:alert] = 'Alert message!'在渲染方法调用之前放置一个,我想你会发现你的方法是有效的.

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

  • 似乎是最新未发布的指南中修复的错误:http://edgeguides.rubyonrails.org/layouts_and_rendering.html (2认同)

Per*_*heo 26

尝试

  def bye
    @counter  = 4
    flash.now[:error] = "Your book was not found"
    render :index
  end
Run Code Online (Sandbox Code Playgroud)


Kar*_*bur 8

通常你会做类似的事情:

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

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

if @user.save
  redirect_to users_path, :notice => "User saved"
else
  render :action => :new, :alert => "You haz errors!"
end
Run Code Online (Sandbox Code Playgroud)

...however, that isn't valid for ActionController::Flash#render.

But, you can extend ActionController::Flash#render to do exactly what you want:

Create config/initializers/flash_renderer.rb with the following content:

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
Run Code Online (Sandbox Code Playgroud)

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