简体   繁体   English

ruby on rails link_to delete 方法不起作用

[英]ruby on rails link_to delete method not working

I am trying to delete a post using the code below:我正在尝试使用以下代码删除帖子:

<%= link_to 'Destroy', post, :method => :delete, :onclick => "return confirm('Are you sure you want to delete this post?')" %>

which does not work... it simply redirects me back to the post (posts/:id}这不起作用......它只是将我重定向回帖子(posts/:id}

however, if i use the following code it works但是,如果我使用以下代码,它就可以工作

<%= button_to 'Destroy', post, method: :delete, :onclick => "return confirm('Are you sure you want to delete this post?')" %>

is it possible to make link_to behave as button_to in this case?在这种情况下是否可以使link_to表现为button_to

EDIT: destroy controller function编辑:销毁 controller function

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

    respond_to do |format|
      format.html { redirect_to posts_url }
      format.json { head :no_content }
    end
  end

log when i click the destroy button:当我点击销毁按钮时记录:

Started GET "/posts/14" for 127.0.0.1 at 2012-10-21 15:38:28 +0300
Processing by PostsController#show as HTML
  Parameters: {"id"=>"14"}
  Post Load (0.4ms)  SELECT `posts`.* FROM `posts` WHERE `posts`.`id` = 14 LIMIT 1
  Rendered posts/show.html.erb within layouts/application (0.6ms)
  User Load (0.4ms)  SELECT `users`.* FROM `users` WHERE `users`.`id` = 1 LIMIT 1
Completed 200 OK in 7ms (Views: 5.4ms | ActiveRecord: 0.8ms)
[2012-10-21 15:38:28] WARN  Could not determine content-length of response body. Set content-length of the response or set Response#chunked = true

routes:路线:

  devise_for :users

  resources :users

  resources :posts

  match '/about' => 'about#index'

  # You can have the root of your site routed with "root"
  # just remember to delete public/index.html.
  root :to => 'index#index'

  # See how all your routes lay out with "rake routes"

  # This is a legacy wild controller route that's not recommended for RESTful applications.
  # Note: This route will make all actions in every controller accessible via GET requests.
  # match ':controller(/:action(/:id))(.:format)'
  match '*a', :to => 'error#routing'

You must be add你必须添加

//= require jquery
//= require jquery_ujs

in javascripts/application.js file在 javascripts/application.js 文件中

second, check in layout file,其次,检查布局文件,

javascript_include_tag "application"

is include or not?是包括还是不包括?

Hope this help.希望这有帮助。

Solution:解决方案:

I had commented out this from application.js when i created the project我在创建项目时从 application.js 中注释掉了这个

// This is a manifest file that'll be compiled into application.js, which will include all the files
// listed below.
//
// Any JavaScript/Coffee file within this directory, lib/assets/javascripts, vendor/assets/javascripts,
// or vendor/assets/javascripts of plugins, if any, can be referenced here using a relative path.
//
// It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the
// the compiled file.
//
// WARNING: THE FIRST BLANK LINE MARKS THE END OF WHAT'S TO BE PROCESSED, ANY BLANK LINE SHOULD
// GO AFTER THE REQUIRES BELOW.
//
//= require jquery
//= require jquery_ujs
//= require_tree .

so re-adding it in solved the problem所以重新添加它解决了问题

您是否在布局文件中包含了这一行?

<%= javascript_include_tag "application" %>

This is the Rails way:这是 Rails 的方式:

<%= link_to 'Destroy', post, confirm: 'Are you sure?', method: :delete %>

If the post isn't deleted then the problem lies in your controller.如果帖子未被删除,则问题出在您的控制器上。 Are you sure you've correctly implemented the #destroy action?您确定您已正确实施#destroy操作吗? What's the output you're getting in your server logs?您在服务器日志中得到的输出是什么?

UPDATE: Change your action to:更新:将您的操作更改为:

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

  respond_to do |format|
    if @post.destroy
      format.html { redirect_to posts_url }
      format.json { head :no_content }
    else
      format.html # do something here
      format.json { head :no_content }
    end
  end
end

It's possible to have a working link_to without jQuery可以在没有 jQuery 的情况下使用 link_to

I've found the best process to make a working delete link for ruby on rails without jQuery!我找到了在没有 jQuery 的情况下为 ruby​​ on rails 创建工作删除链接的最佳过程! We need to work with 3 things:我们需要处理三件事:

  1. Adding destroy method in articles_controller.rbarticles_controller.rb 中添加destroy 方法
  2. routes.rb setup route.rb设置
  3. LINK_TO tag LINK_TO标记

Let's Start...开始吧...

Adding destroy method in articles_controller.rb在articles_controller.rb 中添加destroy 方法

At first, we will add def destroy ... end in articles_controller.rb , lets open:首先,我们将添加def destroy ... end in articles_controller.rb ,让我们打开:

# app/controllers/articles_controller.rb

  def destroy
    @article = Article.find(params[:id])
    @article.destroy
    params[:id] = nil
    flash[:notice] = "Art has been deleted"
    redirect_to :action => :index
  end

Here这里

  1. in the 1st line, we're calling a variable '@article' which will find and select the ID parameters of the article on rails console from our database.在第一行中,我们调用了一个变量“@article”,它将从我们的数据库中在rails 控制台上查找并选择文章的ID参数。 Then,然后,
  2. in 2nd line, the @article variable will make the destroy command in the console.在第二行中,@article 变量将在控制台中执行 destroy 命令。 then,然后,
  3. in 3rd line: the id params will be deleted and在第三行:id 参数将被删除和
  4. in 4th line, a notice will flash in application page "Art has been deleted" and also will show in console that, found nothing in the database.在第 4 行,应用程序页面中将出现一条通知“艺术已被删除”,并且还会在控制台中显示,在数据库中什么也没找到。
  5. In 5th line, after the destroying process completed, we will be redirected to the article index page.在第 5 行,销毁过程完成后,我们将被重定向到文章索引页面。

This is the main factor which will give the destroying command.这是给出破坏命令的主要因素。 and make the link_to working.并使 link_to 工作。

Setup routes.rb设置路由.rb

BUT WAIT We need 2 routes for the destroy page which are:但是等等我们需要 2 条销毁页面的路由,它们是:

  1. A GET protocol setup GET 协议设置
  2. A DELETE protocol setup删除协议设置

In routes just add:在路线中只需添加:

  resources :articles, except: [:destroy] # this will add all get request links automatically except destroy link

  post '/articles/new' => 'articles#create'
  post '/articles/:id' => 'articles#update'
  post '/articles/:id/edit' => 'articles#update' # this 3 lines are needed for other forms purpose

  # we need this 2 lines for our delete link_to setup
  delete 'articles/:id/delete' => 'articles#destroy', as: 'articles_delete'
  get '/articles/:id/delete' => 'articles#destroy'
  

Here这里

  1. The 2nd last line is declaring the DELETE method,最后第二行声明DELETE方法,

    • 'articles/:id/delete' will be the link structure in post link tag (known as: anchor tag in HTML) for every single post, 'articles/:id/delete'将是每个帖子的帖子链接标签(在 HTML 中称为:锚标签)中的链接结构,
    • '=>' is pointing the link structure to the controller tag which is 'articles#destroy' , '=>'将链接结构指向控制器标签,即'articles#destroy'
    • then we defined the path text by setting ** as: 'articles_delete'** which we will use as: 'articles_delete_path' or 'articles_delete_url' in link_to tag.然后我们通过将 ** 设置为:'articles_delete'** 来定义路径文本,我们将在 link_to 标签中将其用作:'articles_delete_path' 或 'articles_delete_url'。

Then然后

  1. in last line, we defined the get request for the delete link which will give us a working link like "https://2haas.com/articles/1/delete" except "/articles/1/destroy" that means we can customize our delete link from this 2 methods setup with more additional information..在最后一行,我们定义了删除链接的获取请求,它将为我们提供一个工作链接,如“https://2haas.com/articles/1/delete”,除了“/articles/1/destroy”,这意味着我们可以自定义我们从这 2 种方法设置中删除链接以及更多附加信息..

Last sweetest delete output最后最甜蜜的删除输出

The desired link_to tag所需的 link_to 标签

we can use this to get proper delete link_to tag which will work.我们可以使用它来获得正确的删除link_to标签,这将起作用。

<%= link_to 'Delete Article', articles_delete_path, method: :delete %>
<%= link_to 'Delete Article', articles_delete_url, method: :delete %>

<% obj.each do |post| %>
<%= link_to 'Delete Article', articles_delete_path(post), method: :delete %>
<% end %>

AND that's done except jQuery并且除了 jQuery 之外已经完成了

Thanks for reading this answer properly.!感谢您正确阅读此答案。!

HAPPY PROGRAMMINGS快乐编程

Make sure that there is no space after the param确保参数后没有空格

def destroy
        @post = Post.find(params[:id])
        @post.destroy
        redirect_to posts_path, :notice => "Your post has been deleted successfully."
end

Check the whitespaces.检查空格。

I checked all the comments here.我检查了这里的所有评论。 All the includes were set correctly.所有的包含都正确设置。 But I noticed that deleting articles did not work, while deleting comments would work.但是我注意到删除文章不起作用,而删除评论则起作用。 After rewriting some code and checking here and there, I found two files that looked identically in the editor, but one version would work and one would not work!在重写了一些代码并在这里和那里检查之后,我发现两个文件在编辑器中看起来完全相同,但是一个版本可以工作,一个版本不工作!

curry-blog/app/views/articles/index.html.erb:咖喱博客/app/views/articles/index.html.erb:

<h1>Listing Articles</h1>
<%= link_to 'New article', new_article_path %>
<table>
  <tr>
    <th>Title</th>
    <th>Text</th>
    <th colspan="3"></th>
  </tr>
 
  <% @articles.each do |article| %>
    <tr>
      <td><%= article.title %></td>
      <td><%= article.text %></td>
      <td><%= link_to 'Show', article_path(article) %></td>
      <td><%= link_to 'Edit', edit_article_path(article) %></td>
      <td><%= link_to 'Delete', article_path(article),
              method: :delete,
              data: { confirm: 'Are you sure?' } %></td>        
    </tr>
  <% end %>
</table>

However, looking at the files with xxdiff I found that in one version only tabs where used, while the other also used blanks.但是,查看带有xxdiff的文件时,我发现在一个版本中只使用了选项卡,而另一个版本也使用了空白。 Probably, from copy pasting code from the tutorial.可能是从教程中复制粘贴代码。 Replacing the blanks with tabs did therefore fix the problem.因此,用标签替换空白确实解决了问题。

If using link_to with :delete method you must be sure to have javascript active:如果将link_to:delete方法一起使用,您必须确保 javascript 处于活动状态:

Note that if the user has JavaScript disabled, the request will fall back to using GET.请注意,如果用户禁用了 JavaScript,则请求将回退到使用 GET。

As seen in docs文档所示

If you don't want to be dependent on javascript you can use button_to instead of link_to .如果您不想依赖 javascript,您可以使用button_to而不是link_to

Firstly try checking the HTTP post method being generated in the logs.首先尝试检查日志中生成的 HTTP post 方法。 If it is "Get", it won't trigger a delete action in the controller, regardless of routes etc. It has to be a an HTTP Delete method.如果它是“Get”,它不会在控制器中触发删除操作,不管路由等。它必须是一个 HTTP 删除方法。

In the latest versions of Rails including rails 6+, where including jquery UJS etc is not an option / easy, You should use button_to helper instead of link_to .在包括 rails 6+ 在内的最新版本的 Rails 中,包括 jquery UJS 等不是一个选项/容易,您应该使用button_to 助手而不是 link_to It creates a delete HTTP post.它创建了一个删除 HTTP 帖子。

https://apidock.com/rails/ActionView/Helpers/UrlHelper/button_to https://apidock.com/rails/ActionView/Helpers/UrlHelper/button_to

it's working perfectly for me, <%= button_to 'Delete', article_path(article), method: :delete %>它对我来说很完美, <%= button_to 'Delete', article_path(article), method: :delete %>

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

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