开发者

Polymorphism Alternative Question

开发者 https://www.devze.com 2023-01-31 22:42 出处:网络
Here is how I\'m handling comments without using actual Rails polymorphism: class Comment < Active Record::Base

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

开发者_如何学Go

Should self.commentable = Commentable.new be self.commentable = Commentable.create! instead?


Rather than using make_commentable, use the Rails-provided build_commentable method.

0

精彩评论

暂无评论...
验证码 换一张
取 消