【问题标题】:Rails destroy nested entries.Rails 会破坏嵌套条目。
【发布时间】:2012-04-28 02:10:01
【问题描述】:

我的应用设置如下:

-为类别和产品生成支架。

-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

结束

谢谢!

【问题讨论】:

    标签: ruby-on-rails ruby-on-rails-3 ruby-on-rails-3.1


    【解决方案1】:

    看看这个: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
    

    【讨论】:

      【解决方案2】:

      你需要在 category.rb 中

      has_many :products, :dependent => :destroy
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2015-02-13
        • 2015-04-28
        • 1970-01-01
        • 2016-01-09
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多