I'm learning Rails myself, and trying to do CRUD - let's call a model I'm working with "Project
".
Create, Read and Update done by scaffold
are working fine, but Delete doesn't: when we press default "Destroy this project" button - an object, we are trying to delete, stays inside of table even after page refreshing, and it's kind of troubling.
Every operation has it's own route, which represents url to call for it. Be it show.html.erb (projects
), new.html.erb (new_project_path
), or edit.html.erb (edit_project_path(@project)
) - all those forms have their own route variables to reffer when calling, but deletion - doesn't.
If we look at show.html.erb form, generated by scaffold
, we see, that "Destroy this project" button reffers to @project
variable itself, which is needed to send data from code behind to html-page: <%= link_to "Destroy this project", @project, method: :delete, class:"btn btn-danger" %>
. Meanwhile, rails routes
command tells us, that responsive delete-URL exists, but still, there is no route variable for it (like new_project, edit_project, and so on)
Here are buttons I have created to call for delete from showing-page (all having no effect on db):
<%= link_to "Destroy this project", @project, class:"btn btn-danger"%>
<%= link_to "Destroy this project", @project, method: :delete, class:"btn btn-danger" %>
<%= link_to "Destroy this project", {:action => "destroy", :controller => "projects", :id => @project.id}, { :confirm => 'Are you sure?', :method => :delete, :remote => true} %>
Here is a Delete-function, called by link_to
:
def destroy
@project.destroy #Projects.find(params[:id]).destroy does not make difference either
respond_to do |format|
format.html { redirect_to project_url, notice: "Project was successfully destroyed." }
format.json { head :no_content }
end
end
I also tried to call for Delete-operation manually. Here are links I tried to call "Delete" through (with "No route matches" exception):
http://localhost:3000/projects/9/destroy
http://localhost:3000/projects/9#destroy
http://localhost:3000/projects/9/projects#destroy
http://localhost:3000/projects/9/project#destroy
The key question is: how do I call for Delete-operation for model, generated by scaffold
, from link_to
tag?
---EDIT---
I have just fixed the issue.
Key to the solution was in changing @project.destroy
line to Project.find(params[:id]).destroy
. Seems strange to me either, because of meaning the same on http://localhost:3000/projects/7, but it helped. Also, I rewrited redirection settings like this to prevent nil pointing error.
respond_to do |format|
format.html { redirect_to projects_url, notice: "Project was successfully destroyed." }
format.json { head :no_content }
end
(Changed redirect_to
parameter from project_url
to projects_url
)
Fitting caller-button must be like this:
<%= button_to "Destroy this project", @project, method: :delete, %>