繁体   English   中英

如何在Rails中使has_many关系无效

[英]How to invalidate has_many relationship in 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

我很可能会错过一些显而易见的东西。 某些假设的self-courses.invalidate方法。

不在他们的公共API中,但是您可以在AssociationCollection类上尝试reset方法。

看日志:

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

扩展了我不能说的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")

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM