每当我在视图中输入,更新或删除某些内容时,都会显示一条消息,通知我此操作已成功,但只有在我转到新页面时才会退出。我想知道如何插入一个按钮,以便这个消息加起来。我目前正在发送department_controller.rb:
def edit
end
# POST /departments
# POST /departments.json
def create
@department = Department.new(department_params)
respond_to do |format|
if @department.save
format.html { redirect_to @department, notice: 'Departamento criado com sucesso.' }
format.json { render :show, status: :created, location: @department }
else
format.html { render :new }
format.json { render json: @department.errors, status: :unprocessable_entity }
end
end
end
# PATCH/PUT /departments/1
# PATCH/PUT /departments/1.json
def update
respond_to do |format|
if @department.update(department_params)
format.html { redirect_to @department, notice: 'Departamento atualizado com sucesso.' }
format.json { render :show, status: :ok, location: @department }
else
format.html { render :edit }
format.json { render json: @department.errors, status: :unprocessable_entity }
end
end
end
答案 0 :(得分:0)
如果您使用仅限HTML 作为回复,请确保您要在其中显示通知的ERB文件在页面顶部显示以下HTML标记,因为看起来你在其他页面中没有这个标签:
<p id="notice"><%= notice %></p>
答案 1 :(得分:0)
在你的例子中
format.html { redirect_to @department, notice: 'Departamento criado com sucesso.' }
notice:
使用了flash
。 flash
消息存储在会话中,但在呈现后会消失。如果您希望这些消息持续存在,则必须避免使用闪存。将它们存储在会话中可能是一种选择,但会话中的空间非常有限。以下是在重置会话之前会持续的消息示例,这可能是用户每次注销时都会出现的。
# in controller action
session[:messages] ||= []
session[:messages] << 'Departamento criado com sucesso.'
# in view
<%= session[:messages] %>
听起来你希望能够一个一个地解散(关闭?)这些消息。这意味着要创建一个控制器动作来处理这种行为:
# in config/routes.rb
resources :messages, only: :delete
# in app/controller/messages_controller.rb
class MessagesController
def destroy
session[:messages]&.delete_at(params[:id])
redirect_to :back
end
end
# In your layout i.e. app/views/layouts/application.html.erb
<%= session[:messages]&.each_with_index do |message, i| %>
<%= message %>
<%= link_to 'X', message_path(i), method: :delete %>
<% end %>