I have two models:
# photo.rb
belongs_to :batch, inverse_of: :photos
# batch.rb
has_many :photos, inverse_of: :batch
I wanted to have a batch destroyed only when it's last photo is destroyed.
# photo.rb
belongs_to :batch, inverse_of: :photos, dependent: :destroy
Will delete the batch if I destroy any of it's photos. Is there any easy way to do this in rails? or do I have to do something ugly like handle it in photos#destroy
?
It must be done manually. The following code is for Rails 4.x.
An easy way to do it is to use an after_destroy
filter in the photo model to check if the parent batch is empty, and if so, destroy it.
# photo.rb
after_destroy :destroy_empty_batch
def destroy_empty_batch
batch.destroy if batch.photos.empty?
end
However, it is bad design to allow one model to manipulate objects of another model. The proper way to do it is in the controller. Instead of using a filter in the model, just add two lines to the photos controller:
# photos_controller.rb
def destroy
batch = @photo.batch # set a batch pointer
@photo.destroy
batch.destroy if @batch.empty? # check batch, destroy if empty
# ...respond_to block...
end
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.