Update single common column in multiple has-many relationships rails I want to update a single column in 4 tables. All relationships are has-many among them.


Private schools has many private classes
Private classes has many lesson plans
Lesson plans has many quizzes
Lesson plans has many documents


The code I am working with is:

@private_school.private_classes.each do |private_class|
            private_class.lesson_plans.each do |lesson_plan|
              lesson_plan.update_attribute("price_type", @private_school.price_type)
              lesson_plan.quizzes.update_attribute("price_type", @private_school.price_type)
              lesson_plan.documents.update_attribute("price_type", @private_school.price_type)
            end
          end


Is this a best approach to follow or is there any more option to tackle this? What are best practices about this scenario?
(Converted a comment into this answer)

If all the records should use @private_school.price_type as their own price_type, then make them fetch it from the school they belong to - don't duplicate the same value across a bunch of tables when you already have it in one place. Keep the database normalized.

Simplest way to do this is to add a price_type method to each of the non-school models. The method simply fetches and returns &lt;belongs_to relation&gt;.price_type. I.e. Document#price_type would call its owner's method, which would be LessonPlan#price_type, which would call it's owner, etc.. until it hits the school's price_type attribute.

It's not the most efficient as it may need to load some records in the chain, but it's a start.