如何使Rails中的has_many关系无效

时间:2010-08-16 21:16:38

标签: ruby-on-rails activerecord caching

在我的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

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

3 个答案:

答案 0 :(得分:5)

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

观看日志:

s = Student.first
s.courses       # Hits db
s.courses       # Hits cache 
s.courses.reset # No db
s.courses       # Hits db

答案 1 :(得分:1)

扩展我不能说的140个字符...你可以通过使用附加到关联的一些Rails方便方法来避免需要使关系无效。比方说,我有一个User和一个Project模型:

class Project < ActiveRecord::Base
  # Backing table has :id, :user_id, :name, and :description columns
end

class User < ActiveRecord::Base
  has_many :projects
end

user = User.first # Assuming you have some users already

# Creates a new project named "Some Project" with description "Some Description"
# and sets the project's user_id to user.id. Also handles in-memory user.projects
# updating.
user.projects.create(:name => "Some Project, :description => "Some Description")

答案 2 :(得分:0)

您应该查看update_attribute方法中的构建,这些方法通过SQL进行更新,但具有更改本地属性的优势。