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)
Per*_*heo 26
尝试
def bye
@counter = 4
flash.now[:error] = "Your book was not found"
render :index
end
Run Code Online (Sandbox Code Playgroud)
通常你会做类似的事情:
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)
归档时间: |
|
查看次数: |
31752 次 |
最近记录: |