Bot
Bot

Reputation: 1011

Why relative position of associations and callbacks in a rails model affecting the results

I have a model Indent which has many indent_items and has many shipments through indent_items.

class Indent < ActiveRecord::Base

  before_destroy :check_for_shipments # WORKS HERE

  has_many :indent_items, inverse_of: :indent, :dependent => :destroy
  has_many :shipments, :through => :indent_items

  # before_destroy :check_for_shipments # DOESN"T WORK HERE

  private
  def check_for_shipments
   # Should not be allowed to delete if there are any shipments.
   if self.shipments.count > 0
     errors.add(:base, "Cannot delete indent because shipments are there.")
     return false
   end    
  end

end

I guess it may be because if callback is mentioned after the association, all indent items gets marked for deletion and the shipment count check returns zero always.

But this shouldn't happen. Or may be I am missing something here. I don't know.

I am using rails 3.2.8.

Upvotes: 0

Views: 90

Answers (1)

Kuldeep
Kuldeep

Reputation: 884

This is the desired behaviour of rails and if you want that before_destroy callback is executed before the shipment has destroyed(because of dependent: :destroy option) then you have to use the prepend option on the before_destroy callback.

e.g.

class Indent < ActiveRecord::Base

  has_many :indent_items, inverse_of: :indent, :dependent => :destroy
  has_many :shipments, :through => :indent_items

  before_destroy :check_for_shipments, prepend: true #this will work

  private

  def check_for_shipments
   # Should not be allowed to delete if there are any shipments.
   if self.shipments.count > 0
     errors.add(:base, "Cannot delete indent because shipments are there.")
     return false
   end    
  end

end

And for the further reference you can read from here.

Upvotes: 1

Related Questions