Are my ActiveRecord associations setup correctly? (simple message board application)
Basically I want a Topic to have many Posts and Posts to have many Comments. If a Post gets destroyed I want it's Comments to be destroyed. If a Topic is deleted, I want it's Posts and Comments destroyed. Does the code below accomplish this? And is the has_one :topic
line necessary?
topic.rb:
class Topic < ActiveRecord::Base
has_many :posts, :dependent => :destroy
end
post.rb:
class Post < ActiveRecord::Base
belongs_to :topic, :depen开发者_开发百科dent => :destroy, :touch => true
has_one :topic
has_many :comments, :dependent => :destroy
end
comment.rb:
class Comment < ActiveRecord::Base
belongs_to :post, :dependent => :destroy, :touch => true
end
Should I be using the Ancestry
gem for this? Would that make this even more simple? Thanks for reading my questions. Any assistance would be greatly appreciated.
1) has_one :topic
is unnecessary, with the belongs_to
you already declare the association.
2) :dependent => :destroy
goes on the has_many side for your requirements. If you place them on the belongs_to side you will destroy a Topic once destroying one of his posts, leaving orphan a lot of other posts.
This is the code you're looking for:
topic.rb:
class Topic < ActiveRecord::Base
has_many :posts, :dependent => :destroy
end
post.rb:
class Post < ActiveRecord::Base
belongs_to :topic, :touch => true
has_many :comments, :dependent => :destroy
end
comment.rb:
class Comment < ActiveRecord::Base
belongs_to :post, :touch => true
end
精彩评论