【问题标题】:Custom validation: referencing parent association from model created by accepts_nested_attributes_for自定义验证:从 accept_nested_attributes_for 创建的模型中引用父关联
【发布时间】:2012-09-07 23:32:59
【问题描述】:

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

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

为什么在验证期间questionAnswer#need_title? 中是nil

【问题讨论】:

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


    【解决方案1】:

    我假设您正在创建带有嵌套答案的问题。对于新创建的答案,其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
    

    当从嵌套属性构造新答案时,这应该分配反向关联(从答案到问题),并且您的验证器将得到非 nil question,正如它所期望的那样。

    【讨论】:

    • 谢谢我按照本文Nested attributes validations中的描述解决了这个问题。我试过你的变种,但它没有用。我不知道为什么,在构建后的rails c 中,父级存在,但在验证时我看到了相同的错误消息。
    猜你喜欢
    • 1970-01-01
    • 2018-10-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-30
    • 2021-12-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多