有没有办法访问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
。有任何想法吗?
答案 0 :(得分:1)
@
中的@commentable
是不必要的,因为它不是模型的实例变量。所以:
def increase_count()
commentable.inc(:comments_count, 1)
end
def decrease_count()
commentable.inc(:comments_count, -1)
end
应该这样做。