Rails 为什么我的魔法字段不生效

sforce100 · November 30, 2012 · Last by James_Zhan replied at March 14, 2013 · 2486 hits
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.

应该先找到 question 然后 @question.answers.build

You need to Sign in before reply, if you don't have an account, please Sign up first.