Destroy Function in Ruby On Rails does not work - ruby-on-rails

I've used he rails engine to create a demo app. Everything works fine, except the "Destroy" function deos not do anything.
There is no error message.
Can anyone guess as to why nothing would happen, even though there is no error message?
The function (auto-created) is:
def destroy
#term = Term.find(params[:id])
#term.destroy
respond_to do |format|
format.html { redirect_to terms_url }
format.json { head :ok }
end
end
and the HTMl part is:
<td><%= link_to 'Destroy', term, confirm: 'Are you sure?', method: :delete %></td>
I dont even get the confirmation question.
Checked, and JavaScript is enabled.

It's a pretty common question, sounds like you're not including the javascript that shows the confirmation and implements the delete method across all browsers that don't support it - did you include the rails javascript libraries?
Rails 3.1
<%= javascript_include_tag "application" %>
Rails 3
<%= javascript_include_tag :defaults %>
see link_to delete url is not working

I think your link_to signature is wrong. Try:
<%= link_to 'Destroy', term, :confirm => 'Are you sure?', :method => :delete %>

Related

Destroy method in rails and Mongoid

I am trying to delete a particular "work" from an array of "works" which is embedded in user.
In my work.html.erb file in views:-
<% #works.each do |f| %>
<%= link_to 'Destroy', profiles_destroy_path(f), data: {:confirm => 'Are you sure?'}, :method => :delete %>
<% end %>
And in my controller:-
def destroy
#work = current_user.works.find(params[:id])
#work.destroy
respond_to do |format|
format.html { redirect_to root_url }
end
end
I am getting following error:-
Mongoid::Errors::InvalidFind at /profiles/destroy.56fa4d2f498b5908a002e2e8
P.S. - I am new to rails.
Please check params[:id] is not nil. There's no :id at session start and you get the Mongoid::Errors::InvalidFind exception above.
delete action doesn't have path by default..
<%= link_to 'Destroy', profiles_path(f), data: {confirm: 'Are you sure?'}, method: :delete %>
That will call the destroy action from your controller.
And make sure params[:id] is not nil.
PS: use rails 4 annotation (avoid using rockets (=>))
There may be an error in Juan's answer.
I believe you want:
<%= link_to 'Destroy', profile_path(f), method: :delete, data: {confirm: 'Are you sure?'} %>
Note: the singular "profile_path" instead of "profiles_path"
This is because the destroy action uses the same path as the show action, but uses a DELETE method instead of a GET. (Which you can observe by running "rake routes" in your terminal and comparing the two routes.)

ROR delete action not working

I am beginner to ROR and I am following this tutorial http://guides.rubyonrails.org/getting_started.html.
So according to this tutorial I want to delete one post. But its not working it showing this error The action 'destroy' could not be found for PostsController
My post controller delete method looks like
def destroy
#post = Post.find(params[:id])
logger.debug "***********************: #{#post.id}"
#post.destroy
redirect_to posts_path
end
In routes I mentioned resource resources :posts but still it is giving error for destroy action. Am I doing something wrong. Need Help.
Did you mention the method as delete in your views?
If you are using Rails 4, you should do:
<%=link_to 'Destroy', post_path(post), method: :delete, data: { confirm: 'Are you sure?' } %>
In Rails 3:
<%=link_to 'Destroy', post_path(post), method: :delete, confirm: 'Are you sure?' %>

Rails 4 link_to Destroy not working in Getting Started tutorial

I am working through the Getting Started tutorial (creating a Blog) and the link_to Destroy is not functioning properly. In the terminal it always interprets it as #SHOW.
In reading similar issues I have learned that the Delete must be converted to a POST for the browser to interpret it. This doesn't seem to be happening.
I have run into the same problem using Destroy in the Lynda.com Rails course as well, so it leads me to believe it is something in my development environment. I am using Rails 4, Ruby 2.00p274, MySQL, WEBrick for the HTTP server on a MacBook Pro Lion.
in the terminal session when Destroy is selected:
Started GET "/posts/4" for 127.0.0.1 at 2013-08-09 13:45:20 -0600
Processing by PostsController#show as HTML
Parameters: {"id"=>"4"}
Post Load (0.6ms) SELECT "posts".* FROM "posts" WHERE "posts"."id" = ? LIMIT 1 [["id", "4"]]
Rendered posts/show.html.erb within layouts/application (0.4ms)
Completed 200 OK in 13ms (Views: 8.6ms | ActiveRecord: 0.6ms)
In the ports-controller.rb:
def destroy
#post = Post.find(params[:id])
#post.destroy
redirect_to action: :index
end
In the index.html.erb:
<% #posts.each do |post| %>
<tr>
<td><%= post.title %></td>
<td><%= post.text %></td>
<td><%= link_to 'Show', post %></td>
<td><%= link_to 'Edit', edit_post_path(post) %></td>
    <td><%= link_to 'Destroy', { action: :destroy, id: post.id }, method: :delete, data: { confirm: 'Are you sure?' } %></td>
</tr>
<% end %>
In the routes.rb
Blog::Application.routes.draw do
resources :posts do
resources :comments
end
root to: 'welcome#index'
end
Try this
<%= link_to 'Destroy', post, method: :delete, data: { confirm: 'Are you sure?' } %>
Make sure gem 'jquery-rails' is in gemfile and jquery_ujs is included in app/assets/javascripts/application.js file
//= require jquery
//= require jquery_ujs
Source: https://github.com/rails/jquery-ujs
I had the same issue, for rails 4.2.X. Checked all my javascript files but could not make it work. if u look closely at the server request u will be missing 'authenticity_token' in the params, so user gets logged out.
In rails 4.1 and above u have to use button_to instead of link_to
I solved the problem, just by adding in assets/javascripts/application.js
//= require jquery_ujs
Make sure that you have a Delete REST method via rake routes.
DELETE /articles/:id(.:format) articles#destroy
I've got the same problem only with this blog version as I'm doing both.
http://blog.8thcolor.com/en/2011/08/nested-resources-with-independent-views-in-ruby-on-rails/
I'm also trying to learn how to use the web console and pry within it.
My problem is that binding.pry doesn't show up in destroy method but will in show. That tells me it must be a bad link right? It's not getting to the destroy method even. Thank you all for your answers. We do have to try things don't we?
Trying
<td><%= link_to 'Destroy', { action: :destroy, id: post.id }, method: :delete, data: { confirm: 'Are you sure?' } %></td>
is not going to work for that one.
Here's what he has
<td><%= link_to 'Destroy', [comment.post, comment], :confirm => 'Are you sure?', :method => :delete %></td>
because you only want to delete the comment here.
But combining things so far like the following gives no errors but I still have no binding.pry from the destroy method in the controller.
<td><%= link_to 'Destroy', [comment.post, comment], method: :delete, data: { confirm: 'Are you sure?' } %></td>
and I never get the confirmation like you would expect.
So do try to figure out what's going on with the jquery as suspect.
I can confirm that was my case but the rest I'll leave for nubes because this will show up in a google search.
Started GET "/posts/4" for 127.0.0.1 at 2013-08-09 13:45:20 -0600
This is the problem. The delete link is using GET http verb even though you used method: delete in your link.
Check out the following SO thread
include below line in js
//= require jquery_ujs
include gem:
gem 'jquery-rails'
Destroy Link:
<%= link_to "Logout", destroy_user_session_path %>
I had the same issue and realized that I had created my rails app with -J which is the same as --skip-javascript.
You need JavaScript enabled for this to work; the lack of a popup to confirm the delete is a dead giveaway.
I had exactly this problem and it was caused by triple-clicking the Guide's code block and copy/pasting the code straight into my editor (ST2 on OSX).
You should check that the generated HTML for the link looks like this:
<a data-confirm="Are you sure?" data-method="delete" href="/posts/3/comments/3" rel="nofollow">Destroy Comment</a>
If it doesn't, but instead looks like the below, then the Javascript won't be applied:
Destroy Comment
The large gaps between the href and the unparsed Ruby are caused by the non-breaking spaces (unicode character \u00a0) used in the Guide being copied into your script.
I'm not sure why this doesn't cause a script parse error.
I had the same problem as Barry. Make sure you're copy/pasting correctly in your /app/views/index.html.erb file and inspect the html that is rendered.
I had same problem. In my case, a i had change \app\views\layouts\application.html.erb file from
<%= stylesheet_link_tag 'application', media: 'all', 'data-turbolinks-track' => true %>
<%= javascript_include_tag 'application', 'data-turbolinks-track' => true %>
to
<%= stylesheet_link_tag 'default', media: 'all', 'data-turbolinks-track' => true %>
<%= javascript_include_tag 'default', 'data-turbolinks-track' => true %>
to avoid my very first Rails problem. But it apparently mangled JavaScript execution and caused Destroy issue.
Therefore rollback your \app\views\layouts\application.html.erb file to its original state, and treat this problem as here
Rails ExecJS::ProgramError in Pages#home?
in evedovelli answer (about coffeescript gem in windows).
I got the same problem. I work out by this way:
My env. is:
A. ruby 2.2.4p230 (2015-12-16 revision 53155) [x64-mingw32]
B. Rails 4.2.5
C. Browser: Firfox 44.02
add include js in html page because delete function will use js to handle.
<%= javascript_include_tag "application" %>
add skip_before_action :verify_authenticity_token to controller for prevent InvalidAuthenticityToken in AdsController#destroy
add link_to into your web page
<%= link_to 'Delete', post, method: :delete, data: {confirm: "Are you sure?"}%>
Now, I can use link_to to delete a record from my page.
Using the button_to method instead of link_to seemed to work, minus the fact that it was not confirming(which I felt was important).
In my case, I was using react-on-rails and had multiple layouts.
Adding <%= javascript_include_tag 'application', 'data-turbolinks-track': 'reload' %> to my hello-world layout fixed the problem.

Improperly routed Rails Destroy method on nested resource

I have a List object, with nested Tasks. I have created a page that displays individual tasks, and also a page that allows a user to edit individual tasks. I now want to add the ability to delete a task from a list on the tasks edit page. Using the following code
<%= link_to 'Delete this task',#task, confirm: 'Are you sure?', method: :delete %>
yields
undefined task_path method
This code is on the show.html.erb page, where I call #task to display all of the data stored within the task, so I believe that this issue may be a routing error of some kind, however I cannot seem to figure it out.
The related controller method is
def destroy
#task = Task.find(params[:id])
#task.destroy
respond_to do |format|
format.html { redirect_to list_tasks_path(#task) }
format.json { head :ok }
end
end
I thought that with the delete method the #task I supplied would just be sent to the destroy method via params, but this error seems to be showing that this isn't exactly how it works. So how can I properly destroy a nested resource in Rails?
edit:
Here is the route file with nested resources:
MyApp::Application.routes.draw do
resources :lists do
resources :tasks
end
get "home/index"
root :to => 'home#index'
end
Thank you for your help!
You should have #list setup, or use #task.list (assuming you have a belong to relationship), and you could do the following:
<%= link_to "Delete this task", list_task_path(#task.list, #task), confirm: "Are you sure?", method: :delete %>
Cheers!
Try this:
<%= link_to 'Delete this task', list_task_path(#list, #task), confirm: 'Are you sure?', method: :delete %>
Or if you want it more compact (like you've written it):
<%= link_to 'Delete this task', [#list, #task], confirm: 'Are you sure?', method: :delete %>
Either way, since it's a nested resource, you must pass in both the #list and #task objects.

How to create a delete link for a related object in Ruby on Rails?

So let's say I have Posts and Comments and the url for show is /posts/1/comments/1. I want to create a link to delete that comment in the comments controller destroy method. How do I do that?
<%= link_to 'Destroy', post_comment_path(#post, comment),
data: {:confirm => 'Are you sure?'}, :method => :delete %>
in comments controller:
def destroy
#post = Post.find(params[:post_id])
#comment = Comment.find(params[:id])
#comment.destroy
respond_to do |format|
format.html { redirect_to post_comments_path(#post) }
format.xml { head :ok }
end
end
Since some time ago, the confirm option has to be included in a data hash, otherwise it will be silently ignored:
<%= link_to 'Destroy', post_comment_path(#post, comment),
data: { confirm: 'Are you sure?' }, method: :delete %>
Sometimes when you have <span>, <i> or nested elements inside of a <a> tag this way link_to use is difficult. You can inseted use raw HTML which is easy to handle, like so:
<a class="btn btn-sm" href="/blogs/<%=#blog.id%>" data-method="delete">
<i class="pg-trash"></i><span class="bold">Delete</span>
</a>
Given you have #post variable with your post object
Before Rails 7
<%= link_to 'Delete comment', post_comment_path(#post, comment),
method: :delete, data: {confirm: 'Are you sure?'} %>
Rails 7 (with Turbo, out of the box)
<%= link_to 'Delete comment', post_comment_path(#post, comment),
data: {turbo_method: :delete, turbo_confirm: 'Are you sure?'} %>
In rails 7.0.4.2
You can use destroy method this way 'turbo gem'
<%= link_to 'Delete', user, data: {turbo_method: :delete, turbo_confirm: 'Are you sure?'} %>
Turbo gives you the speed of a single-page web application without having to write any JavaScript. Turbo accelerates links and form submissions without requiring you to change your server-side generated HTML. It lets you carve up a page into independent frames, which can be lazy-loaded and operate as independent components. And finally, helps you make partial page updates using just HTML and a set of CRUD-like container tags. These three techniques reduce the amount of custom JavaScript that many web applications need to write by an order of magnitude. You can install 'turbo' in terminal by:
gem install turbo-rails -v 1.0.1
Or in Gemfile and bundled it.
gem 'turbo-rails', '~> 1.0', '>= 1.0.1'
Then
bundle install

Resources