In my Rails app, I have a class with a has_many relationship. For the sake of efficiency, I want to do some direct SQL to update many rows in the database at once, and then I want to mark the has_many relationship as no longer valid. If later code accesses the has_many relationship, I want it to reload the data. But I obviously want to skip the SQL unless it is necessary.
So for example:
class Student
has_many courses # may have a :condition clause or some such
def some_method
# For some reason, we want to change all courses in here, not
# just a single row.
ActiveRecord::Base.connection.execute("UPDATE courses SET location = #{new_location}")
# Not sure if we'll later do anything with self.courses, so I need to invalidate
# that relationship. Could do self.courses.reload right here, but I don't want to
# do the SQL if it isn't necessary; the cache only lasts until the end of the
# current page request.
end
end
I may well be missing something rather obvious. Some hypothetical self.courses.invalidate method.