'Error with a link action to delete a record
I am creating a link to delete a record from the database, the link calls a destroy method that is responsible for doing the deletion.
Link:
<%= link_to "Eliminar el articulo", options = {:action => destroy, :id => @article.id}, html_options = {:method => :delete, :data => { :confirm => '¿Estas seguro?' }, :class => 'btn btn-danger'} %>
Routes.rb:
delete 'articles/:id' => 'articles#destroy'
Controller:
def destroy
@article = Article.find(params[:id])
@article.destroy
redirect_to root_path
end
To be more concise, I would like to say that I can locate the problem in the link since what fails is :action => destroy but if I remove the link, what it does is go to the same page instead of delete the record.
The error: undefined local variable or method `destroy' for #ActionView::Base:0x000000000395d0
The text is translated using Google Translate. To see the original question click here
Solution 1:[1]
The error: undefined local variable or method `destroy' for #ActionView::Base:0x000000000395d0
destroy variable is not defined in the view... you should use a symbol instead (:action => :destroy)
<%= link_to "Eliminar el articulo", options = {:action => :destroy, :id => @article.id}, html_options = {:method => :delete, :data => { :confirm => '¿Estas seguro?' }, :class => 'btn btn-danger'} %>
However, I suggest to use the route helpers:
delete 'articles/:id' => 'articles#destroy', as: :article
# or user rails resources
# resources :articles, only: [:destroy]
<%= link_to "Eliminar el articulo", article_path(@article), method: :delete, data: { confirm: 'Are you sure?' } %>
Solution 2:[2]
Try this
= form_tag(article_path(@article), method: :delete, remote: true) do
= button_tag(type: 'submit', class: 'btn btn-danger') do
= content_tag(:strong, 'Delete')
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | Vahe Sedrakyan |
