访问has_many关系的父级

时间:2012-07-20 02:08:47

标签: ruby-on-rails-3 mongoid

有没有办法访问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。有任何想法吗?

1 个答案:

答案 0 :(得分:1)

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

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

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

应该这样做。