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
这样的实例变量是一个好主意,可以在保存回调之前和之后进行通信吗?还有更好的方法吗?
答案 0 :(得分:2)
只需使用around_save
回调。
查看完整的回调列表http://guides.rubyonrails.org/active_record_validations_callbacks.html#callbacks-overview
以下是如何使用它的示例:Rails: around_* callbacks