首页 > 解决方案 > 如何始终在 Rails 应用程序中保存嵌套项(即使它们没有被更改)?

问题描述

在我的 Rails 6 应用程序中,我有这个关联:

class Project < ApplicationRecord

  has_many :tasks, :dependent => :destroy, :autosave => true

  accepts_nested_attributes_for :tasks, :allow_destroy => true

end

现在,当我将 aproject与其嵌套一起保存时tasks,任务仅在至少一个属性发生更改时才会更新。

由于特定于我的应用程序/用例的原因,我希望tasks始终数据库中更新,尽管(即使它们都没有改变!)当我点击保存时。

如何做到这一点?

我希望添加:autosave => true会有所作为,但不幸的是它没有。

标签: ruby-on-railsrubyactiverecordnested-forms

解决方案


您可以对 Project 进行回调:

class Project < ApplicationRecord

  before_save :touch_tasks

  def touch_tasks
    tasks.all.touch_all
  end
end

https://apidock.com/rails/ActiveRecord/Relation/touch_all


推荐阅读