Fields_for and accepts_nested_attributes_for in rails 6

0

I have noticed something strange. For I have a rails app which has user model.

User has one lab

Lab belongs to user.

User has two attributes , username and age.

Username is mandatory on creation and age is mandatory when updating.

I am using fields_for and accepts_nested_attributes_for creation of parent as well as child record in a single form.

Lab has four attributes:

:first_reading, :second_reading both mandatory on create , :third_reading, :forth_reading both mandatory on ‘update’.

When creating an object, all my validations run on create, username for user and first_reading and second_reading for lab.

When editing the record, when my age is null, validation runs perfect, but when my lab’s third and forth reading is null record is submitted. Why is this so? For user’s age when blank, validation runs, and for lab’s third and forth reading blank, validation doesn’t run.

Is there any solution to this.

This is my github repo link. You can go through the structure from here. GitHub - muhammadans414414/Demo

Your lab model looks like this:

class Lab < ApplicationRecord
  belongs_to :user

  validates :igg_first_reading, presence: {message: "please select first igg reading"}, on: :create
  validates :igm_first_reading, presence: {message: "please select first igm reading"}, on: :create
  validates :igg_second_reading, presence: {message: "please select second igg reading"}, on: :update
  validates :igm_second_reading, presence: {message: "please select second igm reading"}, on: :update
end

I do not see any validations for third & fourth readings.