如何使Rails中的has_many关系无效

Chr*_*ton 0 activerecord caching ruby-on-rails

在我的Rails应用程序中,我有一个has_many关系的类.为了提高效率,我想做一些直接SQL来一次更新数据库中的许多行,然后我想将has_many关系标记为不再有效.如果以后的代码访问has_many关系,我希望它重新加载数据.但我显然想跳过SQL,除非有必要.

例如:

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
Run Code Online (Sandbox Code Playgroud)

我可能会遗漏一些相当明显的东西.一些假设的self.courses.invalidate方法.

Tys*_*aza 5

不在他们的公共API中,但您可以在AssociationCollection类上尝试重置方法.

看日志:

s = Student.first
s.courses       # Hits db
s.courses       # Hits cache 
s.courses.reset # No db
s.courses       # Hits db
Run Code Online (Sandbox Code Playgroud)