mystic cola
mystic cola

Reputation: 1643

Rails: Flash Messages not appearing anywhere

So let's say I have code like this:

class PostsController < InheritedResources::Base 
  # Add before_filter here and devise should handle the redirection if the user is not signed in.
  before_filter :authenticate_user!, only: [:vote_up]

  def vote_up
  begin
  current_user.vote_for(@post = Post.find(params[:id]))
  redirect_to [@post]
  flash[:success] = "You have voted successfully"
rescue ActiveRecord::RecordInvalid
  redirect_to [@post]
  flash[:error] =  "You have already voted"
  end
 end

end

Neither of the messages "You have voted successfully" or "You have already voted" are being shown.

In my view I have:

enter code here

<p id="notice"><%= notice %></p>
    <%= @post.embed .html_safe %>
    <header>
        <h7><%= @post.name %></h7>
    </header>
<h8><%= @post.title %></h8>
<article>
<%= @post.content .html_safe %>

<p>
<%= link_to 'Back', posts_path %> |
<%= link_to('Vote for this song!', vote_up_post_path(@post), :method => :post) %></p>

<p><id="notice"><%= notice %></p>

No dice. I'm still not getting flash messages anywhere. Any idea what I'm doing wrong?

Upvotes: 1

Views: 4591

Answers (4)

N.Rafael
N.Rafael

Reputation: 1

Your code is like: <p><id="notice"><%= notice %></p>

You need <p id="notice"><%= notice %></p>

Upvotes: 0

techdreams
techdreams

Reputation: 5585

The best way to do it

<% if flash[:notice] %>
    <div class="notice"><%= flash[:notice] %></div>
<% end %>

Upvotes: 0

logesh
logesh

Reputation: 2662

You have used

flash[:success] = "You have voted successfully"

in your controller and you have called

<%= notice %>

in your views. You have to change either in your controller or in your views.

You can add

format.html { redirect_to @post, notice: 'You have voted successfully.' }

in your controller and you will get the message that you require.

Upvotes: 2

Bachan Smruty
Bachan Smruty

Reputation: 5734

You should set the flash before redirect_to

And in your view

<p>
  <%= flash[:success] unless flash[:success].blank? %>
  <%= flash[:error] unless flash[:error].blank? %>
</p>

You can check this link as well

Upvotes: 1

Related Questions