多态性替代问题

时间:2010-12-22 05:35:36

标签: ruby-on-rails polymorphism

以下是我在不使用实际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!吗?

1 个答案:

答案 0 :(得分:0)

不使用make_commentable,而是使用Rails提供的build_commentable方法。