Pratik Khadloya
Pratik Khadloya

Reputation: 12879

communicating between activerecord before_save and after_save

before_save :set_path_name_csv, :if => Proc.new { |audience| audience.new_record? || audience.name_changed? || audience.parent_id_changed? }
after_save :set_path_ids_csv, :if => Proc.new { |audience| audience.path_ids_csv.nil? || @path_name_csv_updated }

def set_path_name_csv
  if self.parent
    self.path = self.parent.ancestors.map(&:name).unshift(self.parent.name).unshift(self.name).reverse.join(" > ")
  else
    self.path = self.name
  end
  @path_name_csv_updated = true
end

def set_path_ids_csv
  if self.parent
    self.path_ids_csv = self.parent.ancestors.map(&:id).unshift(self.parent.id).unshift(self.id).reverse.join(",")
  else
    self.path_ids_csv = self.id.to_s
  end
  self.send(:update_without_callbacks)
end

Is using an instance variable like @path_name_csv_updated a good idea to communicate between the before and after save callbacks? Is there a better way?

Upvotes: 1

Views: 634

Answers (1)

phoet
phoet

Reputation: 18845

just use around_save callback instead.

have a look at the full list of callbacks http://guides.rubyonrails.org/active_record_validations_callbacks.html#callbacks-overview

here is an example of how you can use it: Rails: around_* callbacks

Upvotes: 2

Related Questions