class Question
include Mongoid::Document
field :answers_count, :type => Integer, :default => 0
has_many :answers, :dependent => :destroy
end
class Answer
include Mongoid::Document
field :content, type: String
belongs_to :question, :inverse_of => :answers
end
q = Question.create.......
a = Answer.create....
q.answer << a # 或 a.question = q
answers_count # 还是0
给
belongs_to :question, :inverse_of => :answers, :counter_cache => true
a=Answer.new。。。。
报错:
Problem:
Invalid option :counter_cache provided to relation :question.
Summary:
Mongoid checks the options that are passed to the relation macros to ensure that no ill side effects occur by letting something slip by.