我有一个模型Profile
,其中有很多gallery_items
。
class Profile < ApplicationRecord
# ...
has_many :gallery_items, dependent: :destroy
accepts_nested_attributes_for :gallery_items, allow_destroy: true
我想在更改图库项目时在Profile
中触发代码。是否可以在不修改GalleryItem
类的情况下执行此操作?
您可以使用配置文件上的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