Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails :dependent => destroy, want to call another action instead of destroy

I have a has_many :through model that works perfectly.

  has_many :varietals
  has_many :grapes, :through => :varietals, :dependent => :destroy

I would like to call another action instead of :destroy. In fact, I don't want to nullify the item OR destroy it, I want to update the record status field from 1 to 0 instead of destroy the record.

How to call a custom method instead of destroy ? I suppose I can do that in the model itself... Thanks.

Where to put this method ? In the master model or in the model where the record will be destroyed ?

EDIT:

I'm sorry but I think I didn't enough explain my problem. My problem is not only to so something after the master model is destroyed. I want to custom the destroy action in the Varietal model itself even if the master record is not destroyed.

Something like:

class Varietal < ActiveRecord::Base

    private
      def destroy
        self.update_attributes(:status => 0)
      end
end

Actually this action is not called...

like image 839
alex.bour Avatar asked Feb 17 '12 10:02

alex.bour


2 Answers

You can use before_destroy to put your custom logic there. E.g.,

before_destroy :reset_status

def reset_status
  ...
end

Check here for more details.

like image 83
Phyo Wai Win Avatar answered Oct 16 '22 16:10

Phyo Wai Win


You just need add a callback on before_destroy or after_destroy and manipulate your associations. By example

after_destroy :do_on_grapes

def do_on_grapes
  grapes.map(&:to_do)
end
like image 24
shingara Avatar answered Oct 16 '22 14:10

shingara