Validation in Child Model in Nested Attribute - Rails

Viewed 691

This are my files:

word.rb

class Word < ActiveRecord::Base
  has_many :word_answers, dependent: :destroy
  accepts_nested_attributes_for :word_answers, allow_destroy: true,
    reject_if: lambda {|attribute| attribute[:word_id].blank?}
end

word_answer.rb

class WordAnswer < ActiveRecord::Base
  belongs_to :word
  validates :content, uniqueness: true, presence: true
end

Is there any method that I can valiidate validates :content, uniqueness: true, presence: true of word_answer.rb in word.rb?

Rails 4.

I tried validates_associated :word_answers but it doesn't work.

I want to achieve is

(1) If I submit Word, it will give an error if there is no WordAnswer.

(2) If I submit Word, it will give an error if there is a BLANK WordAnswer.

(3) If a validation is WordAnswer is wrong, It will give an error if I submit Word.

2 Answers
Related