Rails 6:模型可以知道对其has_many关联之一所做的更改吗?

问题描述 投票:0回答:1

我有一个模型Profile,其中有很多gallery_items

class Profile < ApplicationRecord
  # ...

  has_many :gallery_items, dependent: :destroy
  accepts_nested_attributes_for :gallery_items, allow_destroy: true

我想在更改图库项目时在Profile中触发代码。是否可以在不修改GalleryItem类的情况下执行此操作?

ruby-on-rails rails-activerecord ruby-on-rails-6
1个回答
0
投票

您可以使用配置文件上的after_touch挂钩。只要确保表示GalleryItem与其关联关联的配置文件即可。

class GalleryItem < ApplicationRecord
  belongs_to :profile, touch: true
end

class Profile < ApplicationRecord
  has_many :GalleryItems
  after_touch :my_fancy_method

  private
    def my_fancy_method
      puts 'Doing some stuff after a GalleryItem was created/updated'
    end
end
© www.soinside.com 2019 - 2024. All rights reserved.