ruby-on-rails - 跳过 :touch associations when saving an ActiveRecord object

标签 ruby-on-rails ruby activerecord

有没有办法在保存时跳过更新与:touch关联的关联?

设置:

class School < ActiveRecord::Base
  has_many :students
end

class Student < ActiveRecord::Base
  belongs_to :school, touch: true
end

我希望能够在跳过触摸的地方执行如下操作。

@school = School.create
@student = Student.create(school_id: @school.id)
@student.name = "Trevor"
@student.save # Can I do this without touching the @school record?

你能做到吗?像 @student.save(skip_touch: true) 这样的东西会很棒,但我还没有找到类似的东西。

我不想使用像 update_column 这样的东西,因为我不想跳过 AR 回调。

最佳答案

从 Rails v4.1.0.beta1 开始,正确的做法是:

@school = School.create
@student = Student.create(school_id: @school.id)

ActiveRecord::Base.no_touching do
  @student.name = "Trevor"
  @student.save
end

关于ruby-on-rails - 跳过 :touch associations when saving an ActiveRecord object,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16221586/

相关文章:

ruby-on-rails - 如何重新初始化 ruby​​ on Rails 项目

ruby - 格式化日期时间字符串

javascript - 如何进行 Ajax update_attributes?

mysql - Rails Activerecord + MySQL 查询没有给出我期望的结果

ruby - 在迁移中从 lambda 指定默认值

ruby-on-rails - 如何在 Rails 6 中请求自定义 JS 文件

ruby-on-rails - 在我的应用程序中为 Mongoid 创建索引?

ruby-on-rails - Rails created_at 时间戳顺序与 id 顺序不一致

ruby-on-rails - 如何将 ruby​​ gem 的代码包含到主 rails 项目中?

ruby-on-rails - Rails 有许多动态条件子句