在我的Rails應用中,我有一個has_many關係的類。爲了提高效率,我想直接使用SQL來更新數據庫中的許多行,然後我想將has_many關係標記爲不再有效。如果後面的代碼訪問has_many關係,我希望它重新加載數據。但我顯然想要跳過SQL,除非有必要。如何使Rails中的has_many關係失效
因此,例如:
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
我可能失去了一些東西相當明顯。一些假設的self.courses.invalidate方法。
這正是我所需要的。謝謝! – ChrisInEdmonton 2010-08-17 15:10:12
公共API,來自has_many文檔:collection(force_reload = false) – 2013-10-20 16:28:17