What am I missing with this Ruby on Rails Destroy Action? - ruby-on-rails

I'm trying to learn Ruby on Rails and I'm getting stuck. When I try to delete a resource, nothing happens. It looks like it just refreshes the page. Looking around at other places on the Internet, I'm currently guessing that it has something to do with Javascript, but I'm not quiet sure what.
For reference, I'm following this guide and getting stuck on section 7.5:
https://guides.rubyonrails.org/getting_started.html#deleting-an-article
I've been bumbling around the Internet for a couple hours now trying to figure this out to no avail. Here's a list of other questions I've looked at this I think might be related to this, but from which I haven't been able to find a solution:
Ruby on rails destroy not working
Destroy path not working in Ruby on Rails
So, here's my controller action in app/controllers/articles_controller.rb
class ArticlesController < ApplicationController
def show
#article = Article.find(params[:id])
end
def destroy
#article = Article.find(params[:id])
#article.destroy
flash[:success] = "The article has been destroyed."
redirect_to articles_path, status: :see_other
end
end
config/routes.rb is pretty simple
Rails.application.routes.draw do
resources :articles
end
And here's how I'm trying to call that controller action from a view in app/views/articles/show.html.erb. I've seen a few different notations for how to call the delete method, none of them seem to work.
<ul>
<li>
<%= link_to "Destroy", article_path(#article), data: {
turbo_method: :delete,
turbo_confirm: "Are you sure?"
} %>
</li>
<li>
<%= link_to "Delete", article_path(#article), :method => :delete %>
</li>
<li>
<%= link_to "Defenestrate", article_path(#article), method: :delete %>
</li>
</ul>
And it's those links that just seem to do... nothing. As per some of things I found online, I tried including these lines (not at the same time) in app/views/layouts/application.html.erb
<%= javascript_include_tag :defaults, 'data-turbolinks-track' => true %>
<%= javascript_include_tag "defaults", 'data-turbolinks-track' => true %>
<%= javascript_include_tag "application", 'data-turbolinks-track' => true %>
But they all throw a similar error, something like:
Sprockets::Rails::Helper::AssetNotFound in Articles#show
Showing app/views/layouts/application.html.erb where line #10 raised:
The asset "defaults.js" is not present in the asset pipeline.
I'm assuming it's referring to some location either in app/assets or lib/assets but I'm not sure.
I tired adding gem "jquery-rails" to the Gemfile and including the following lines in app/assets/config/manifest.js
//= require jquery
//= require jquery_ujs
But... all to no avail. I seem to be completely stuck, so I'm hoping someone may be able to point me in the right direction. For reference, here are some versions
Rails 7.0.4
ruby 3.1.2p20 (2022-04-12 revision 4491bb740a) [x86_64-linux]
Fedora 37 (Server Edition)

Try with button_to in rails 7
<%= button_to "Destroy", #article, method: :delete %>

Related

How to use x_editable_rails for editing comments

Not sure why i am getting this error message when implementing gem x_editable_rails to allow comments to be edited without users being brought to a separate edit page.
x_editable_rails demo app shows that perhaps the right way should be <%= editable #comment, :content %>, but because I am looping all comments in the #comments instance variable, doing that throws an error too.
EDIT
I changed the line of code from <%= editable #comments.comment %> to <%= editable [comment.article, comment], :content, url: edit_article_comment_path(comment.article, comment) %> and now, its showing
undefined method `xeditable?' error.
I have added the below helper method and added this (helper_method :xeditable?) to application controller. (I don't use cancan so i have added a dummy can? as suggested on this stackoverflow post.
module ApplicationHelper
def xeditable?
current_user.xeditable?
end
def can?(role, object)
true
end
end
_comments.html.erb
<% #comments.each do |comment| %>
<%= editable [comment.article, comment], :content, url: edit_article_comment_path(comment.article, comment) %>
<%= link_to "Delete comment", [comment.article, comment], method: :delete %>
<%= link_to "Edit comment", edit_article_comment_path(comment.article, comment) %>
<% end %>
routes.rb
resources :articles do
resources :comments
end
Routing
The original error you posted indicates you do not have a route for APP_DOMAIN/comments/:id, and that's confirmed by your routes -- comment is a nested resource in your routing, routed like APP_DOMAIN/articles/:id/comments/:id.
Note that for unusual routing (i.e. not a typical Rails naming pattern), x-editable-rails allows you to specify your path. Maybe comments are routed through another name, like url: post_critique_path(#comment.post, #comment). I see you have now done this, though I'm not sure if it is necessary since your routing is standard pratice.
Note that I have not tested this myself. The README is not super clear on what are the allowed or expected values for :url. And, confusingly, the gem has a :nested option – which appears to be about setting the title HTML attribute.
Application helper methods
For your next error, it appears you are implementing the advice from this answer. But I believe you have missed a line, and your ApplicationHelper module should look like this:
module ApplicationHelper
helper_method :xeditable?, :can
def xeditable?
current_user.xeditable?
end
def can?(role, object)
true
end
end

Rails destroy does not work and forwards to a wrong link

I am totally new to rails and struggle with the easiest stuff. I have the following problem:
When I try to destroy a search (from my model search) it does not work and I get redirected to "/search.48 (the search with id 48). It gives me the notice "We're sorry, but something went wrong." and in the console it says something with POST. Neither the search is deleted nor the redirect_to search_path is working. What am I doing wrong?
This is my controller:
def show
#searches = current_user.searches
end
def destroy
#search = Search.find(params[:id])
#search.destroy
flash[:success] = "Search deleted"
redirect_to search_path
end
This is my view show:
<% #searches.each do |search| %>
<%= search.title %>
<%= search.description %>
<%= button_to "delete", search, method: :destroy %>
My routes.rb:
get 'search' => 'searches#show'
resources :searches
And I also included <%= javascript_include_tag 'application' %> in the application.html.erb as well as //= require jquery and //= require jquery_ujs in the application.js file.
So I really can't find my mistake. Can someone help me?
In your view file, the code for the button should look like:
<%= button_to "delete", search, method: :delete %>
Note the method is :delete, not :destroy. It's a little confusing, because 'delete' is the REST verb, but 'destroy' is the controller action name.
have you tried:
<%= button_to "Delete", { action: "delete", id: search.id },
method: :delete %>
in you view. Also it appears you are redirecting to search_path but I am guessing you want searches_path.
I got it! In my router I wrote get 'search' => 'searches#show' and somehow my controller was confused with the search_path. Since I renamed it to get 'mysearches' => 'searches#show' and mysearches_path it works perfectly

No route matches [GET] "/links/1/like" with acts_as_votable

I'm trying to implement acts_as_votable gem as shown in this this tutorial
https://www.youtube.com/watch?v=7-1HCWbu7iU
Seems everything is workigng fine, except when I click on upvote or downvote, I get this error:
No route matches [GET] "/links/1/like"
This is the code for upvote / downvote function
<span class="upvote">
<%= link_to like_link_path(link), method: :put, class: "upvote-image" do %>
<% end %>
</span>
This is the routes.rb file:
resources :links do
member do
put "like", to: "links#upvote"
put "dislike", to: "links#downvote"
end
resources :comments
end
Here are the upvote and downvote actions in links_controller
def upvote
#link = Link.find(params[:id])
#link.upvote_by current_user
redirect_to :back
end
def downvote
#link = Link.find(params[:id])
#link.downvote_by current_user
redirect_to :back
end
Any idea on how to resolve this?
Looks like the problem is down to your link having a GET method, rather than PUT:
No route matches [GET] "/links/1/like"
I can only surmise that your link_to code is not written correctly:
<span class="upvote">
<%= link_to like_link_path(link), method: :put, class: "upvote-image" %>
</span>
Your other code looks good. If you test this, the best thing to do will be to show the pure HTML for the link in your question - this will give us the ability to see whether it's being rendered correctly.
I found an answer for this, and I'm posting it here in case there are others with the same problem.
I'm developing on Windows. I had problems with javascript, and followed this solution here:
https://stackoverflow.com/a/31972253/1690091
This removed the javascript related errors that were popping all over the place, but this is NOT the solution. This simply removed js from my app.
The real solution is here:
https://stackoverflow.com/a/28331807/1690091
You need to use a proper version of coffee script, that's compatible with Windows.
To sum things up:
js file was missing from my app, and therefore //= require jquery_ujs was also missing, and that's why all of my links were being called as GET.
#Rich Peck,
Thanks for your help.
Try this
<span class="upvote">
<%= link_to like_path, method: :put, class: "upvote-image" do %>
<% end %>
</span>

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.

why do I keep getting this error: undefined method new_message_path

So I made a quick ruby on rails app (railstutorial twitter clone). My source code is the same as https://github.com/railstutorial/sample_app_2nd_ed.
Then I tried adding replies to the messages with http://railscasts.com/episodes/262-trees-with-ancestry?view=asciicast. My comment is at the bottom BigBoy1337. This is what it says:
I keep getting an error saying
undefined method `new_message_path'
This is in app/views/messages/_messages.html.erb
for
<%= link_to "Reply", new_message_path(:parent_id => message) %>
<% if current_user?(message.user) %>
<%= link_to "delete", message, method: :delete,
confirm: "You sure?",
title: message.content %>
<% end %>
Any idea where to define new_message_path? I tried adding
def new_message_path
end
in app/controllers/message/controllers
...but it didn't work. I have downloaded the source code (https://github.com/BigBoy1337/railscasts-episodes/tree/master/episode-262/messenger-after) and that works! but I cant find where they define new_message_path, yet it works. Why does it work for them, and how can I get it to work for me?
That's a resource route. Try adding the following to routes.rb:
resources :messages
Also, read this: http://guides.rubyonrails.org/routing.html
new_message_path is defined in routes.rb.
Look for this line:
resources :messages
read this to learn about rails routing.

Resources