ruby-on-rails - 如何始终在 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
会有所作为,但不幸的是它没有。
解决方案
您可以对 Project 进行回调:
class Project < ApplicationRecord
before_save :touch_tasks
def touch_tasks
tasks.all.touch_all
end
end
推荐阅读
- json - Scala:如何修复尝试使用 Circe 解码器解码 JSON 的类型不匹配错误
- jenkins - 无法从 Jenkins 签出 GitLab 回购
- javascript - 如何通过属性(在javascript中)关联两个(或更多)对象?
- java - 如何将对象称为方法参数?
- security - Razor 页面与 Blazor 结合使用是否可以防止过度绑定/过度发布/批量绑定攻击?
- javascript - 在jsp中的警报中有换行符
- java - 在 JNA 中映射原始类型,同时保留本机 typedef 类
- bootstrap-4 - 如何在不破坏原始导航栏布局的情况下添加切换栏?
- powershell - 基于通配符检查组的成员资格(Powershell)
- sql - 雪花 sql 选择查询自动化