ruby on rails flash 消息 - :alert :error :notice 和 :success?
Posted
技术标签:
【中文标题】ruby on rails flash 消息 - :alert :error :notice 和 :success?【英文标题】:ruby on rails flash messages - :alert :error :notice and :success? 【发布时间】:2011-11-26 13:23:09 【问题描述】:在我的几个控制器中,我有重定向/闪烁消息
redirect_to products_url, :notice => "message here",
redirect_to states_url, :error => "oops!" etc...
然而,在我的会话控制器中,在成功验证后,我有 flash[:success] = "欢迎!" 重定向到用户
我希望能够在我的其他控制器中执行类似的操作 :success => “耶!”
这主要是为了美观/一致性目的,但 :notice、:alert 和 :error 是唯一可用的 flash 类型/我可以添加其他类型吗?我说得有道理吗?
谢谢!
【问题讨论】:
【参考方案1】:如果您想根据引导警报(成功和警告)访问不同类型的闪存消息样式,请在您的控制器中:
flash[:success] = "This works!"
在你的布局中(很可能是 application.html.erb)
<% if success.present? %>
<p class="alert alert-success"><%= success %></p>
<% end %>
警告和其他引导警报样式也是如此。
【讨论】:
【参考方案2】:我相信如果不做任何更改,这将是您将得到的最接近的结果:
redirect_to user_path(@user), :flash => :success => "Message"
这里有一些 additional notes 关于友好的 Flash 语法添加。
【讨论】:
【参考方案3】:我刚刚发现在 Rails 4 中您可以在应用控制器中注册自定义类型:
class ApplicationController
...
add_flash_types :error, :another_custom_type
end
# app/controllers/users_controller.rb
class UsersController < ApplicationController
def create
...
redirect_to home_path,
error: "An error message for the user"
end
end
# app/views/home/index
<%= error %>
功劳归http://blog.remarkablelabs.com/2012/12/register-your-own-flash-types-rails-4-countdown-to-2013
【讨论】:
以上是关于ruby on rails flash 消息 - :alert :error :notice 和 :success?的主要内容,如果未能解决你的问题,请参考以下文章
Ruby on Rails:运行 rake 命令时出现错误消息
如何正确销毁 ruby on rails 中的关联记录?
如何在考拉,Ruby on Rails 中发送私人消息/访问 Facebook 聊天
Ruby on Rails i18n - 想要在模型中翻译自定义消息