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
272 views
in Technique[技术] by (71.8m points)

ruby on rails - How to display messages (aka flash) without rendering or redirecting

After form submit my controller checks if some conditions. In my case there are three of them:

  1. if user rich maximum of his possibilities of objects tracking
  2. if user already track this object
  3. everything is ok, and request is added to queue

I'd like to inform user about those conditions. I have form with remote: true and now I show the info by render js: "alert('info')" but it looks ugly. I don't want to redirect user somewhere or rerender the form after form submit. I just want to display 'flash' message and wait to another request from user. How can I make it?

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)
  1. Simple approach:

On top of your form page, have a div to store the message:

In your request handler for the remote request in the controller, compute the message to show.

def create
  ...
  @message = get_message
  ...
end

Since it is an ajax request, your view will be a .js.erb file (assuming you are using erb). In that view, just set the message div content as @message:

# create.js.erb
$('#message').text("#{@message}");
  1. Advanced approach:

Alternatively, if you want richer formatting, create a partial for the message formatting and render it in the js.erb file.

For example, I use bootstrap for my styles, and I can make the message look like an alert with an 'x' to close it - so I create a partial to render the alert:

# views/home/_message.html.erb
<div class='alert alert-warning alert-dismissible'>
  <%= message %><button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">&times;</span></button>   
</div>

And in your js.erb you could do this instead,

# create.js.erb
$("#message").html("<%= escape_javascript(render partial: 'home/message', locals: { message: @message } ) %>"); 

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

...