在activerecord before_save和after_save之间进行通信

时间:2012-01-27 21:10:38

标签: ruby-on-rails activerecord

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

使用像@path_name_csv_updated这样的实例变量是一个好主意,可以在保存回调之前和之后进行通信吗?还有更好的方法吗?

1 个答案:

答案 0 :(得分:2)

只需使用around_save回调。

查看完整的回调列表http://guides.rubyonrails.org/active_record_validations_callbacks.html#callbacks-overview

以下是如何使用它的示例:Rails: around_* callbacks