Validation in child model in nested attribute - Rails

advertisements

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.


I don't think if we can add validates :content, uniqueness: true, presence: true to Word method but you can achieve validation for WordAnswer model in Word Model by adding a before_save & before_update filters.

I guess the validations in WordAnswer model will work fine as you want them to when you use nested attributes in the form and it will validate fine.

In other case kindly explain what you actually want to achieve ?