Warm tip: This article is reproduced from stackoverflow.com, please click
alert crud rest ruby-on-rails twitter-bootstrap

How to create alert with redirect_to

发布于 2020-05-08 07:09:02

Hi I want to create an success alert when a gossip was created and return on my home page or put's an danger alert when the validation fail

I've just succeeded to setup the error alert.

Here is my gossip controller :

class GossipsController < ApplicationController
  def index
    @gossips = Gossip.all
  end

  def show
    @gossip = Gossip.find(params[:id])
  end

  def new
    @error = false
  end

  def create
    @gossip = Gossip.new(title: params[:title], content: params[:content], user: User.find(182))

    if @gossip.save
      redirect_to root_path 
    else
      @error = true
      render "new"
    end
  end
end

And here it's my view of new :

<% if @error %>
    <div class="alert alert-danger alert-dismissible fade show" role="alert">
      <strong>Error</strong>
      <ul>
          <% @gossip.errors.full_messages.each do |message| %>
            <li><%= message %></li>
          <% end %>
        </ul>
      <button type="button" class="close" data-dismiss="alert" aria-label="Close">
        <span aria-hidden="true">&times;</span>
      </button>
    </div>
<% end %>   

<h2>Create your own gossip !</h2> <br><br>

<%= form_tag url_for(action: 'create'), method: "post" do %>

    <%= label_tag 'Title :' %> <br>
    <%= text_field_tag 'title'%> <br><br>

    <%= label_tag 'Content :' %> <br>
    <%= text_area_tag 'content'%> <br><br>

    <%= submit_tag "Create Gossip" %>
<% end %>

I've try to do same for the success alert but if i put a @success = true in the controller and <% if @success %> in the index view that don't work. I don't have any ideas.

Tell me if you need some part of my code.

I've tried with flash but that doesn't worked and whatever i want the same style with the error and success alert

Questioner
ffouquet42
Viewed
29
widjajayd 2020-02-23 18:04

create flash message partial app/views/layouts/_flash.html.erb (please give filename with underscore since it partial)

<% flash.each do |key, value| %> 
  <div class="alert alert-<%= key == "success" ? "success" : "danger"  %>">
    <%= value %>
  </div>
<% end %> 

add partial to your app/views/layouts/application.html.erb

<!DOCTYPE html>
<html lang="en">
<head>

</head>
<body>
  ...
  <%= render 'layouts/flash' %> 
  <%= yield %>
</Body>
</html>

in your controller

def create
  @gossip = Gossip.new(title: params[:title], content: params[:content], user: User.find(182))

  if @gossip.save
    flash[:success] = 'success'
    redirect_to root_path 
  else
    flash[:danger] = @gossip.errors.full_messages[0]
    render "new"
  end
end