Deleting a post or a comment currently needs a form so that we can use the _method
trick to trigger a DELETE
action. Rails provides a way that we can do this simply with the link_to
helper.
For example:
<%= link_to 'Delete', post_path(post.id), method: :delete, data: { confirm: "Are you sure want to delete '#{post.title}'?"} %>
This will render into:
<a data-confirm="Are you sure want to delete 'post_title_here'?" rel="nofollow" data-method="delete" href="..." >Delete</a>
Rails monitors the data-method
and data-confirm
data attributes for special processing with a Javascript library that it ships with, the jquery-rails
library. This behavior is called "unobtrusive scripting". It is named "unobtrusive scripting" because the Javascript code that facilitates this is not intertwined with the markup.
In this case, it'll trigger a HTTP DELETE
after the user confirms a dialog box on the UI.
For more about Unobtrusive Scripting behaviors, see:
https://github.com/rails/jquery-ujs/wiki/Unobtrusive-scripting-support-for-jQuery
If we want our link_to
to work as a dynamic form, we need to enable Javascript on our page. To do that we'll need a <script>
tag for our application's main Javascript page. Rails gives us a useful helper for creating this script tag when we need it.
<head>
<title>Blog App</title>
<%= javascript_include_tag 'application' %>
<%= csrf_meta_tags %>
</head>
Notice that we also have csrf_meta_tags
. This dynamically creates a csrf token for our dynamic form to use. Our link_to
dynamic form is using Javascript, and when using Javascript to send a form, we will need to include this csrf meta token. Rails requires it by default.