Projects have many rooms. When I delete a project from the view, the associated rooms are not deleted. Rooms also have many products which should also be deleted when a project is deleted.
Project class
class Project < ActiveRecord::Base
belongs_to :user
has_many :rooms, dependent: :destroy
has_many :products, through: :rooms
end
Projects Controller
class ProjectsController < ApplicationController
def destroy
@project = current_user.projects.find(params[:id])
if @project.delete
redirect_to user_projects_path(@project.user)
end
end
end
Rooms Controller
class RoomsController < ApplicationController
def destroy
@room = Room.find(params[:id])
if @room.delete
redirect_to root_path
end
end
The delete link in the projects show view.
= link_to "Delete", project_room_path(room.project, room), method: :delete, data: { confirm: "Are you sure?" }, title: room.title, class: "btn btn-danger"
Try changing the the destroy action to call the destroy method on the instance variable rather than delete.
class ProjectsController < ApplicationController
def destroy
@project = current_user.projects.find(params[:id])
if @project.delete
redirect_to user_projects_path(@project.user)
end
end
end
According to the documentation on Active Record Associations, "has_many :through associations have records in join tables, as well as the associated records. So ... ... it is assumed that deletion on an association is about removing the link between the owner and the associated object(s), rather than necessarily the associated objects themselves. So with ... has_many :through, the join records will be deleted, but the associated records won't."
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments