自定义验证:从accepts_nested_attributes_for创建的模型引用父关联

时间:2012-09-14 19:16:59

标签: ruby-on-rails validation nested-attributes

只有当问题类型为“选择”或“复选框”时,我才需要验证标题的存在:

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在验证过程中nilAnswer#need_title?

1 个答案:

答案 0 :(得分:4)

我假设您正在使用嵌套答案创建问题。对于新创建的答案,其question关联为nil。这是一个老问题addressing the root cause

以下是使用自定义构建方法设置父对象的方法:

class Question < ActiveRecord::Base
  has_many :answers do
    def build(*args)
      answer = super
      answer.question = self.proxy_owner
      answer
    end
  end

  # ...
end

当从嵌套属性构造新答案时,这应该指定反向关联(从答案到问题),并且验证器将按预期得到非零question

相关问题