Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flash doesn't clear after being viewed

Here is my create action. It creates a new instance of Message, which is checked with model validations.

Then there is a simple if else loop that sends the message if the model validations were fulfilled and renders the 'new' view if they want to send another. If the model validations weren't fulfilled, it simply renders the 'new' view again.

The flash hash is also populated with relevant information, a success message and an alert 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 don't think I'm doing it right, because the messages stay in the flash. They aren't cleared after they've been viewed once.

How should I ensure that the flash is cleared, as it should be?

Update

This is how the error comes about. I send a message successfully, and I'm routed back to the 'new' view and I receive a 'success' flash. I attempt to send an erroneous message, and I'm routed back to the 'new' view and I receive both the 'success' flash from before, and a 'alert' flash. Very confusing for the user!

The second I browse to another page, both flashes disappear, but that's the problem I think. Something to do with coming back to the same page so Rails doesn't know to clear the flash. Can I force clear the flash?

like image 883
Starkers Avatar asked Nov 16 '13 04:11

Starkers


1 Answers

I think reading the section about flash.now in the rails doc will help clear this up for you: http://guides.rubyonrails.org/action_controller_overview.html#flash-now.

Flash sticks around for the next request. In this case, you aren't issuing a new request after your create action - you are just re-rendering the new view. I think flash.now is what you want to be using here.

I would also say that in your create success case, the create action should be doing a redirect rather than just re-rendering the view. Are redirect_to and render exchangeable? explains the difference between redirecting and rendering

like image 147
arbylee Avatar answered Oct 06 '22 21:10

arbylee