Search code examples
ruby-on-railsruby-on-rails-3destroy

Use before_destroy to delete another model's entry?


So I have a model, let's call it Notes. On the notes, you can but several posts. So the notes model has the line:

 has_many :posts

And the posts model has the line

 belongs_to :note

Now, when a User destroys a post, I want for the note to be destroyed IF it not longer has any other posts.

I thought i would write this code into the post model with before_destroy:

 def delete_note_if_last_post
    if self.note.posts.count == 1
      self.note.destroy
    end
  end

This doesn't work. It shuts down the server based on an "Illegal Instruction". Is there some way to accomplish what I am trying to do?

EDIT: changed the code, as I noticed an error, and now the problem is slightly different.


Solution

  • you can return false to prevent a model from destruction in before_destroy filter

    before_destroy :has_no_post
    

    then in has_no_post

    def has_no_post
     #You can prevent this from deletion by using these options
     #Option1 return false on certain condition  
    return false if posts.any?
    
    #or add an error to errors
    errors << "Can not delete note if it has post" if posts.any?
    #raise an exception 
    raise "Cant delete ..." if blah blah
    

    end