since you have to cache price_type
on every table, you could use callbacks to not have to do this in a... controller action? or wherever. This could be a first step to simplifying.
class Quiz < ApplicationRecord
belongs_to :lesson_plan
before_save :set_price_type
def set_price_type
price_type = lesson_plan.price_type
end
end
class Document < ApplicationRecord
belongs_to :lesson_plan
before_create :set_price_type
before_save :set_price_type
def set_price_type
price_type = lesson_plan.price_type
end
end
class LessonPlan < ApplicationRecord
belongs_to :private_class
has_many :documents
has_many :quizzes
before_save :set_price_type
after_save :update_relationships
def set_price_type
price_type = private_class.price_type
end
def update_relationships
quizzes.update_all(:price_type, price_type)
document.update_all(:price_type, price_type)
end
end
class PrivateClass < ApplicationRecord
belongs_to :private_school
has_many :lesson_plans
after_save :update_relationships
before_save :set_price_type
def set_price_type
price_type = private_school.price_type
end
def update_relationships
lesson_plans.update_all(:price_type, price_type)
document.update_all(:price_type, price_type)
end
end
class PrivateSchool < ApplicationRecord
has_many :private_classes
after_save :update_private_classes
def update_private_classes
private_classes.update_all(:price_type, price_type)
end
end
then you don't have to do anything extra to keep price type up to date.
The much larger and tougher question to answer is why is this variable being cached on each table in the first place? This is going to eventually make maintenance a nightmare. You need to take a hard look at where you are accessing this value and ask yourself if you really need to cache it.
These decisions are made usually in response to slow queries in views or controller actions, but most of the time that slowness can be resolved in better ways. In general, favor query optimization over denormalization