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

sforce100 · 2012年11月30日 · 最后由 James_Zhan 回复于 2013年03月14日 · 2484 次阅读
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

需要 登录 后方可回复, 如果你还没有账号请 注册新账号