dubstep
November 25, 2011, 6:21pm
1
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
Am 24.11.2011 15:55, schrieb Taiwan Vincent:
Could anyone tell me how to destroy all the posts when the board is
destroyed?
Take a look at the :dependent option for associations:
http://guides.rubyonrails.org/association_basics.html
HTH
Norbert
On Thu, Nov 24, 2011 at 8:25 PM, Taiwan Vincent <
[email protected] > wrote:
@post = @board.posts
Could anyone tell me how to destroy all the posts when the board is
[email protected] .
For more options, visit this group at
http://groups.google.com/group/rubyonrails-talk?hl=en .
1)
class Board < ActiveRecord::Base
has_many :posts, :dependent => :destroy
end
posts.each do |post|
post.destroy
end
posts.delete_all
–
Regards
Mukesh Paras Singh
Am 27.11.2011 09:57, schrieb Taiwan Vincent:
format.xml { head :ok }
http://guides.rubyonrails.org/association_basics.html
HTH
Norbert
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
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