The flash does not clear after viewing

Here is my action to create. It creates a new Message instance, which is verified using model validation.

Then there is a simple if else loop that sends a message if the model check has been completed and displays a β€œnew” view if they want to send another. If the model has not been validated, it simply displays the β€œnew” view again.

A flash hash is also populated with relevant information, a successful message and a warning message if the message was successful or not.

def create @message = Message.new(message_params) if @message.valid? Contactform.contact(@message.name, @message.town, @message.email, @message.content).deliver flash[:success] = "Sent message" render 'new' else flash[:alert] = "Alert" render 'new' end end 

However, I do not think that I am doing it right because the messages remain in flash. They are not cleaned after they have been viewed once.

How can I make sure the flash is clean, as it should be?

Update

So an error occurs. I send a message successfully, and I redirect to a "new" look, and get a "successful" flash. I am trying to send an erroneous message, and I am redirected to the "new" view, and I get both a "successful" flash and a "warning". Very confusing for the user!

In the second, I go to another page, both flashes disappear, but I think about this problem. Something has to do with returning to the same page that Rails does not know to clear the flash. Can I clear the flash?

+6
source share
1 answer

I think reading the section on flash.now in the doc rails will help you figure it out: http://guides.rubyonrails.org/action_controller_overview.html#flash-now .

Flash is used for the next request. In this case, you are not sending a new request after your create action - you are just re-viewing the new view. I think flash.now is what you want to use here.

I would also say that in your success creation case, the create action should redirect, not just redraw the view. Redirect_to redirection and rendering? explains the difference between redirection and rendering

+7
source

Source: https://habr.com/ru/post/958180/


All Articles