Search code examples
ruby-on-railsnested-formsnested-attributes

How to populate parent object in nested attribute


I have two model with following association

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

and

    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

Here, when I debug I see that self is nil, and self.article is also nil.

And I get this error

undefined method phase_id for nil:NilClass.

How can I get article object in mytest method?


Solution

  • You should iterate through the children objects in the parent's validation method and add the errors there instead.

    Please see similar question: Ruby on Rails: how to get error messages from a child resource displayed?