简体   繁体   English

如何在Ruby on Rails中显示已删除元素的名称?

[英]How do I display the name of a deleted element in Ruby on Rails?

I have a simple Rails application where I create objects (such as posts). 我有一个简单的Rails应用程序,可以在其中创建对象(例如帖子)。 So far I can edit and delete them, one by one, but now I want to have a <%= notice %> echoing the name of the deleted object after confirming its deletion. 到目前为止,我可以一个一个地编辑和删除它们,但是现在我想让<%= notice %>在确认删除的对象后显被删除的对象的名称。 Is this possible? 这可能吗? If so, how? 如果是这样,怎么办?

This is an extremely common task in Rails, and the idiomatic solution is to forward some data about the deleted record to the subsequent GET request via the the flash array. 这是Rails中极为常见的任务,惯用的解决方案是通过Flash数组将有关已删除记录的一些数据转发到后续的GET请求。

Your controller's destroy action should look something like this: 控制器的destroy动作应如下所示:

def destroy
  @post = Post.find(params[:id])
  @post.destroy

  redirect_to posts_path, notice: "#{@post.name} was deleted"
end

In your index action, you'll be able to access flash[:notice] to get the string generated in the previous action. 在索引操作中,您将可以访问flash[:notice]以获取在上一个操作中生成的字符串。

You need to store the details you want to echo (eg the name) somewhere, because the object itself will be gone after a redirect. 您需要将要回显的详细信息(例如名称)存储在某处,因为对象本身在重定向后将消失。 I would use the flash for that: 我会为此使用flash

# in the controller
def destroy
  thing = Thing.find(params[:id])
  thing.destroy

  redirect_to things_path, :notice => "Thing #{thing.name} was deleted"
end

# in the index view
<% if flash[:notice] %>
  <div class="notice"><%= flash[:notice] %></div>
<% end %>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM