I got a application like following.
A board has many posts
All posts belong to a board
I try to destroy all the posts under a board when I destroy the board.
My destroy function is following.
def destroy
@board = Board.find(params[:id])
@post = @board.posts
@post.destroy
@board.destroy
respond_to do |format|
format.html { redirect_to(boards_url) }
format.xml { head :ok }
end
end
However, it does not work.
Could anyone tell me how to destroy all the posts when the board is
destroyed?
My source code is following.
http://dl.dropbox.com/u/40209252/forum_demo.tar.gz
Take a look at the :dependent option for associations:
<http://guides.rubyonrails.org/association_basics.html>
HTH
Norbert
-
class`` Board ``< ActiveRecord::Base
``has_many ``:posts``, ``:dependent => ``:destroy
end
- posts.each do |post|
post.destroy
end
- posts.delete_all
Hi I got a solution. Here is my destroy function. Many thanks for the
reply.
def destroy
@board = Board.find(params[:id])
@board.posts.destroy_all
@board.destroy
respond_to do |format|
format.html { redirect_to(boards_url) }
format.xml { head :ok }
end
end
You are quoting my post, where I give you a solution that handles
everything with less coding effort in the model, where it belongs... But
fiddling around with a hack in the controller, that simply shouldnt do
such work.
But maybe I am the one who is wrong?
Bye
Norbert