Here is how I'm handling comments without using actual Rails polymorphism:
class Comment < Active Record::Base
belongs_to :commentable, :class_name => "Commentable", :foreign_key => "commentable_id"
end
class Commentable < ActiveRecord::Base
set_table_name "commentable"
has_many :comments, :dependent => :destroy
end
class Post < ActiveRecord::Base
belongs_to :commentable, :class_name => "Commentable", :foreign_key => "commentable_id", :dependent => :destroy
delegate :comments, :to => :commentable
before_create :make_commentable
def make_commentable
self.commentable = Commentable.new
end
end
This works transparently, except the fact that when make_commentable
is called, only sometimes does it create a Commentable record in the database. It seems to always work when using rails s
but very sporadic when from rails c
.
What's up?
EDIT
开发者_如何学GoShould self.commentable = Commentable.new
be self.commentable = Commentable.create!
instead?
Rather than using make_commentable
, use the Rails-provided build_commentable
method.
精彩评论