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

时间:2016-07-22 14:06:18

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

我有以下关联的两个模型

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.

如何在article object方法中获得mytest

1 个答案:

答案 0 :(得分:0)

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

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