Reload in ruby and when to use it.

Consider we have a model student when we access data from this using the following command.

student = Student.take

The variable student contains the data of a student. Each student has enrolled in many courses, which is another model.

On printing the student, we get the following data

{
  id:1,
  name: "Bhanu",
  courses:[{
    id: 2,
    name: "Physics"
  }]
}

Consider if I update the course model,

Update courses set name= 'Astro physics' where id = 2

The expected behavior now the student should have the updated value, but after printing, I’m getting the same result. Why?
Because the student is an in-memory variable, accessing the student doesn’t result in querying the database so it still has the old data.

To resolve this problem, rails provide a function reload which will update the student variable as per the database.

student.reload // this will print
{
  id:1,
  name: "Bhanu",
  courses:[{
    id: 2,
    name: "Astro physics"
  }]
}

Now we get the latest data. So when to use reload?

So whenever there is a change in an object which is an association relationship. we should reload. Here we have a student which is in a has_many relationship with the courses. If there are any indirect changes in courses we should use reload, so reflected changes can be viewed in the student object.

Read Also: Functions in Ruby that make life easy.

To summarise, to reload model, to reload an activerecord, to reload an association for recent changes we should use this function.

Related Post