1

我的应用程序设置如下:

- 为类别和产品生成脚手架。

-Products belongs_to Categories 和 Categories has_many Products。

我目前可以删除/删除单个类别,但是该类别中的产品仍保留在数据库中。我如何能够删除一个类别以及仅包含在该特定类别中的所有产品?

目前我的类别控制器如下所示:

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

respond_to do |format|
  format.html { redirect_to (:back) }
  format.json { head :ok }
end

结尾

谢谢!

4

2 回答 2

3

看看这个: http: //guides.rubyonrails.org/association_basics.html

class Category < ActiveRecord::Base
  has_many :products, :dependent => :destroy
end

class Product < ActiveRecord::Base
  belongs_to :category
end
于 2012-04-27T18:10:01.673 回答
1

你需要里面 category.rb

has_many :products, :dependent => :destroy
于 2012-04-27T17:52:21.487 回答