仅当问题类型为“选择”或“复选框”时,我才需要验证标题的存在:
class Answer < ActiveRecord::Base
belongs_to :question
attr_accessible :title
validate :need_title?
private
def need_title?
errors.add(:need_title, "")) if
((question.type_of_answer == 'select' || question.type_of_answer == 'checkboxes') && title.blank?)
end
end
class Question < ActiveRecord::Base
has_many :answers
accepts_nested_attributes_for :answers, :allow_destroy => true
validates_presence_of :title
end
但是当我创建对象时,我得到了这个异常:
NoMethodError: undefined method `type_of_answer' for nil:NilClass
为什么question
在验证nil
期间Answer#need_title?
?