【问题标题】:How to always save nested items in Rails application (even if they didn't get changed)?如何始终在 Rails 应用程序中保存嵌套项(即使它们没有被更改)?
【发布时间】:2020-08-14 23:54:58
【问题描述】:

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

class Project < ApplicationRecord

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

  accepts_nested_attributes_for :tasks, :allow_destroy => true

end

现在,当我将 project 与其嵌套的 tasks 一起保存时,这些任务只有在它们的至少一个属性发生变化时才会更新。

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

如何做到这一点?

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

【问题讨论】:

    标签: ruby-on-rails ruby activerecord nested-forms


    【解决方案1】:

    您可以对 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

    【讨论】:

    • 谢谢。是的,这将更新任务的updated_at 属性。不过,它不会在Task 模型上运行任何before_save 回调。如何触发这些?
    • 请更新您的问题。你最初写的“我希望任务总是在数据库中得到更新,尽管(即使它们都没有改变!)”它没有指定你需要 before_save 来触发,即使没有属性改变。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-10-20
    • 1970-01-01
    • 1970-01-01
    • 2015-10-05
    相关资源
    最近更新 更多