2

有没有办法在 Mongoid 3 中访问多态模型的父级?我有这种关系

class Project
  ...
  field "comments_count", :type => Integer, :default => 0
  has_many :comments, :as => :commentable
  ...
end

class Comment
  ...
  field "status"
  belongs_to :commentable, :polymorphic => true

  before_validation :init_status, :on => :create
  after_create :increase_count

  def inactivate
    self.status = "inactive"
    decrease_count
  end

  private
  def init_status
    self.status = 'active'
  end

  def increase_count()
    @commentable.inc(:comments_count, 1)
  end

  def decrease_count()
    @commentable.inc(:comments_count, -1)
  end
  ...
end

我希望能够comments_count在评论被停用时更新父关系中的内容,因为count()对孩子进行操作非常昂贵(而且我需要在应用程序中做很多事情)。我有increase_count工作,但我无法访问@commentabledecrease_count@commentable = nil。有任何想法吗?

4

1 回答 1

1

@in是不必要的@commentable,因为它不是模型的实例变量。所以:

 def increase_count()
    commentable.inc(:comments_count, 1)
  end

  def decrease_count()
    commentable.inc(:comments_count, -1)
  end  

应该做的伎俩。

于 2012-07-20T02:39:54.820 回答