【发布时间】: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