为什么accept_nested_attributes_for allow_destroy不起作用?

我有一个嵌套的属性/资源,我正试图破坏。 我想要做的是在销毁关联的life_hack文章对象时销毁审阅对象。 现在我不太确定accepted_as_nested_attributes是如何工作的,但我很确定这是我需要这样做的方式。 下面我有一些定义如此的路线:

Hacklife::Application.routes.draw do devise_for :users root 'life_hacks#index' resources :life_hacks, only: [:new, :index, :create, :show, :destroy] do resources :reviews, only: [:new, :create] end resources :reviews, only: [:show] do resources :comments, only: [:new, :create] end 

以下是我的LifeHack文章模型:

 class LifeHack < ActiveRecord::Base validates :title, presence: true validates :content, presence: true belongs_to :user has_many :reviews, dependent: :destroy accepts_nested_attributes_for :reviews, allow_destroy: true end 

我的评论模型:

 class Review < ActiveRecord::Base validates :title, presence: true validates :body, presence: true validates :rating, presence: true, numericality: { only_integer: true, greater_than: 0, less_than_or_equal_to: 6 } has_many :comments belongs_to :user belongs_to :life_hack end 

现在我不太确定如何解决这个问题。 通过错误的试验,我已经使用了accepted_as_attribute_for allow destroy和常规的has_many destory方法,但没有用。 可能在控制器文件中有错误,或者可能在评论模型中没有指定某些内容? 根据我的理解,如果你有一个嵌套资源,你需要使用accepts_nested_attributes_for:allow_destroy:true,以使其工作。 至少那是activerecord rails guide使它发声的原因。 有什么想法吗? 谢谢。

您可以使用_destroy键来销毁现有记录。

根据此参考指南:

:allow_destroy

如果为true,则使用_destroy键和计算结果为true的值(例如,1,’1,true或’true’)销毁属性哈希中的所有成员。 默认情况下,此选项处于关闭状

如果您只是显示控制器详细信息,我们可以更好地为您提供帮助。 希望能帮助到你 :)