2012-07-20 65 views
2

有沒有辦法在Mongoid 3中訪問多態模型的父項? 我有這個關係訪問has_many關係的父項

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

@ in @commentable是不必要的,因爲它不是您的模型的實例變量。所以:

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

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

應該做的伎倆。

+1

整潔,它的工作原理。 – user2398029 2013-02-23 20:43:35