如何在嵌套属性中填充父对象

How to populate parent object in nested attribute

我有两个模型具有以下关联

class Article < ActiveRecord::Base
  has_many :categories
  accepts_nested_attributes_for :categories, reject_if: proc { |attributes| (attributes['user_id'].blank? || attributes['numbers'].blank?) }, :allow_destroy => true
end

    class Category < ActiveRecord::Base
      belongs_to :article

      validate :mytest

      def mytest
        valid = self.article.phase_id != Category::STD["author"] && self.article.user_id == self.user_id
if !valid
self.article.errors.add(:base, 'Not admin user error')
end
      end
    end

在这里,当我调试时,我看到 self is nilself.article is also nil

我收到这个错误

undefined method phase_id for nil:NilClass.

如何在mytest方法中得到article object

您应该在父级的验证方法中遍历子对象,并在其中添加错误。

请看类似问题:Ruby on Rails: how to get error messages from a child resource displayed?