嗨,我想在创建八卦时创建成功警报,然后在我的主页上返回,或者在验证失败时返回危险警报
我刚刚成功设置了错误警报。
这是我的八卦控制器:
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
这是我对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">×</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 %>
我已经尝试为成功警报做同样的事情,但是如果我@success = true
在控制器和<% if @success %>
索引视图中放了一个不起作用的话。我没什么主意
告诉我您是否需要我的代码的一部分。
我已经尝试过使用Flash,但是它不起作用,无论我想要带有错误和成功警报的相同样式
创建Flash消息的部分app / views / layouts / _flash.html.erb(请给文件名加下划线,因为它是部分的)
<% flash.each do |key, value| %>
<div class="alert alert-<%= key == "success" ? "success" : "danger" %>">
<%= value %>
</div>
<% end %>
向您的app / views / layouts / application.html.erb添加部分
<!DOCTYPE html>
<html lang="en">
<head>
</head>
<body>
...
<%= render 'layouts/flash' %>
<%= yield %>
</Body>
</html>
在您的控制器中
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