Reputation: 4887
I have a nested attribute/resource, that I'm trying to destroy. What I want to do is to destroy a review object, when an associated life_hack article object is destroyed. Now I'm not too sure how the accepted_as_nested_attributes work but I'm pretty sure this is the way that I need to do it. Below i have some routes defined as so:
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
Below is my LifeHack article model:
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
My Review Model:
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
Now I'm not quite sure how to fix this. Through trial by error I've used both the accepted_as_attribute_for allow destroy and the regular has_many destory methods but to no use. Could there be somthing wrong perhaps in a controller file, or maybe there is something that is not being specified in the review model? From what I understand, if you have a nested resource, you need to use an accepts_nested_attributes_for :something allow_destroy: true in order for it to work. At least that's what the activerecord rails guide made it sound. Any thoughts? Thx.
Upvotes: 1
Views: 6516
Reputation: 6918
You can use the _destroy
key to destroy existing records.
As per this reference guide:
:allow_destroy
If true, destroys any members from the attributes hash with a _destroy key and a value that evaluates to true (eg. 1, '1', true, or 'true'). This option is off by default.
If you could just show the controller details, we could better assist you. Hope it helps :)
Upvotes: 3