我有以下关联的两个模型
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 nil
和self.article is also nil
。
我收到此错误
undefined method phase_id for nil:NilClass.
如何在article object
方法中获得mytest
?
答案 0 :(得分:0)
您应该遍历父级验证方法中的子对象,并在其中添加错误。
请参阅类似问题:Ruby on Rails: how to get error messages from a child resource displayed?