【问题标题】:Why doesn't accepts_nested_attributes_for allow_destroy not work?为什么 accept_nested_attributes_for allow_destroy 不起作用?
【发布时间】:2014-06-02 10:33:23
【问题描述】:

我有一个嵌套的属性/资源,我正在尝试销毁它。当关联的 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 方法,但没有用。控制器文件中可能有什么问题,或者审查模型中可能没有指定一些东西?据我了解,如果您有嵌套资源,则需要使用 Accept_nested_attributes_for :something allow_destroy: true 才能使其正常工作。至少这就是activerecord rails guide的声音。有什么想法吗?谢谢。

【问题讨论】:

  • 您使用的是什么版本的导轨?你能附上你的救生控制器吗?

标签: ruby-on-rails activerecord associations


【解决方案1】:

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

根据reference 指南:

:allow_destroy

如果为 true,则使用 _destroy 销毁属性哈希中的任何成员 键和计算结果为 true 的值(例如 1、'1'、true 或 'true')。 此选项默认关闭。

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

【讨论】:

  • 您好,感谢 Rajesh,抱歉回复晚了。我回到我的问题,结果发现我的测试规范有问题。不过谢谢你的回复,我很感激。
猜你喜欢
  • 2023-03-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-03-07
  • 2019-08-06
  • 2016-07-05
相关资源
最近更新 更多