有没有办法在 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
工作,但我无法访问@commentable
(decrease_count
)@commentable = nil
。有任何想法吗?