Ruby on rails 在render方法中使用:alert(或:notice),该方法来自RubyonRails指南,名为';Rails';中的布局和渲染;,不适合我:
在rubyonrails指南中的render方法中使用:alert(或:notice),名为“Layouts and Rendering in Rails”,对我不起作用 这是指南中提供的示例代码:Ruby on rails 在render方法中使用:alert(或:notice),该方法来自RubyonRails指南,名为';Rails';中的布局和渲染;,不适合我:,ruby-on-rails,ruby-on-rails-3.2,Ruby On Rails,Ruby On Rails 3.2,在rubyonrails指南中的render方法中使用:alert(或:notice),名为“Layouts and Rendering in Rails”,对我不起作用 这是指南中提供的示例代码: def index @books = Book.all end def show @book = Book.find_by_id(params[:id]) if @book.nil? @books = Book.all
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
试一试
我不明白为什么Rails指南提到在
render
中使用flash值,因为它们目前似乎只在重定向到
中起作用。我想如果你放一个flash,你会发现你的方法是有效的。现在[:alert]=“alert message!”代码>在渲染方法调用之前
编辑:这是一个,在调用render之前,应该使用单独的方法调用来设置flash 通常您会执行以下操作:
if @user.save
redirect_to users_path, :notice => "User saved"
else
flash[:alert] = "You haz errors!"
render :action => :new
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
Ref:似乎是一个在最新未发布版本的指南中修复的错误:谢谢Ari,刚刚找到了相应的更改。
def bye
@counter = 4
flash.now[:error] = "Your book was not found"
render :index
end
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
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