以下是我在不使用实际Rails多态的情况下处理注释的方法:
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
这是透明的,除了这个事实,当调用make_commentable
时,它有时只会在数据库中创建一条可评论的记录。它似乎总是在使用rails s
时起作用,但在rails c
时非常零星。
怎么了?
修改
self.commentable = Commentable.new
应该是self.commentable = Commentable.create!
吗?
答案 0 :(得分:0)
不使用make_commentable
,而是使用Rails提供的build_commentable
方法。