Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
661 views
in Technique[技术] by (71.8m points)

ruby - rails 4 -- flash notice

I'm still working on my rails 4 demo site, and I'm seeing an odd thing. In the controller it has a line like this:

format.html { redirect_to @widget, notice: 'Widget was successfully created.' }

This renders a flash message in the redirected page, which is expected. However, the css class attached to the message div is alert alert-notice rather than a valid Bootstrap alert class, like alert-info.

Where is the class being set for this flash, and how do I customize it?

Also, if I'm deleting a record via ajax, is there a way to access the core flash container to display the message via js, or do I have to show / hide my own flash message div just for ajax requests?

EDIT: my Michael Hartl inspired layouts/application.html.erb:

<div class="container">
  <% flash.each do |key, value| %>
    <div class="alert alert-<%= key %>"><%= value %></div>
  <% end %>
  <%= yield %>
</div>

Thanks!

EDIT 2:

Perhaps I wasn't clear enough in my original question. I understand exactly how the class is being set in the flash object in this case. I am interested in learning how to use and customize the notice: in the format.html block. It seems there should be a way to pass a class via this notice? Or is this not a core Rails way of doing things?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

In application.html.erb, you would be displaying the flash messages.

Update that code as below

  <% flash.each do |name, msg| %>
    <%= content_tag :div, msg, class: "alert alert-info" %>
  <% end %>

You can add the classes that you want to apply to the flash message in the class option.

EDIT

The class is setup as alert alert-notice because of alert alert-<%= key %> in your code. When you call redirect_to @widget, notice: 'Widget was successfully created.

A flash message would be added in flash hash with key as notice and value as Widget was successfully created., i.e.,

flash[:notice] = "Widget was successfully created."

EDIT #2

format.html { redirect_to @widget, notice: 'Widget was successfully created.' }

notice: 'Widget was successfully created.' is an argument passed to redirect_to method. It is added to flash hash in this method.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...