:alert(或 :notice)与 render 方法的使用,来自 Ruby On Rails 指南,名为“Layouts and Rendering in Rails”,位于 http://guides.rubyonrails.org/layouts_and_rendering.html , 对我不起作用
这是指南中提供的示例代码:
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 Controller ,如下所示:
class HelloController < ApplicationController
def index
@counter = 5
end
def bye
@counter = 4
render "index", :alert => 'Alert message!'
end
end
我的 index.html.erb View 如下所示:
<ul>
<% @counter.times do |i| %>
<li><%= i %></li>
<% end %>
</ul>
访问时
http://localhost:3000/hello/bye
,我看到了索引 View ,即按预期从 1 到 4 的数字列表,但没有“警报消息!”警报显示。我的布局使用它来显示警报消息:
<% flash.each do |k, v| %>
<div id="<%= k %>"><%= v %></div>
<% end %>
最佳答案
我很困惑为什么 Rails 指南提到在 render
中使用 flash 值,因为它们似乎只适用于 redirect_to
在这一刻。我认为如果你输入 flash.now[:alert] = 'Alert message!'
,你会发现你的方法有效。在您的渲染方法调用之前。
编辑:这是一个 flaw in the guides that will be fixed ,您应该在调用渲染之前使用单独的方法调用来设置闪存。
关于ruby-on-rails - Ruby On Rails 指南中名为 'Layouts and Rendering in Rails' 的 :alert (or :notice) with the render method, 的使用对我不起作用:,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15190508/