dependent :: destroy不会删除视图中的依赖项

时间:2014-06-09 03:15:00

标签: ruby-on-rails dependencies has-many-through has-many

项目有很多房间。从视图中删除项目时,不会删除关联的房间。房间也有很多产品,删除项目时也应删除。

项目类

class Project < ActiveRecord::Base
  belongs_to :user

  has_many :rooms, dependent: :destroy
  has_many :products, through: :rooms
end

项目控制器

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

客房控制器

class RoomsController < ApplicationController
    def destroy
        @room = Room.find(params[:id])
        if @room.delete
            redirect_to root_path
         end
     end

项目中的删除链接显示视图。

 = link_to "Delete", project_room_path(room.project, room), method: :delete, data: { confirm: "Are you sure?" }, title: room.title, class: "btn btn-danger"

1 个答案:

答案 0 :(得分:1)

尝试更改destroy操作以在实例变量上调用destroy方法而不是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

根据Active Record Associations上的文档,&#34; has_many:通过关联在连接表中有记录,以及相关记录。所以...... ...假设关联上的删除是关于删除所有者和关联对象之间的链接,而不是必须关联对象本身。因此,使用... has_many:through,连接记录将被删除,但相关记录将被删除。&#34;