From 3431c0b3eeaf284901bd9aa4265c578207d4c820 Mon Sep 17 00:00:00 2001 From: David Heinemeier Hansson Date: Wed, 12 Sep 2018 10:58:23 -0700 Subject: Ensure blank rich text records aren't saved or required --- lib/action_text/attribute.rb | 15 ++++++++++++++- lib/action_text/content.rb | 2 +- 2 files changed, 15 insertions(+), 2 deletions(-) (limited to 'lib/action_text') diff --git a/lib/action_text/attribute.rb b/lib/action_text/attribute.rb index 299c26b29f..67ade42eb1 100644 --- a/lib/action_text/attribute.rb +++ b/lib/action_text/attribute.rb @@ -37,7 +37,20 @@ module ActionText scope :"with_rich_text_#{name}", -> { includes("rich_text_#{name}") } scope :"with_rich_text_#{name}_and_embeds", -> { includes("rich_text_#{name}": { embeds_attachments: :blob }) } - after_save { public_send(name).save if public_send(name).changed? } + before_save do + # If there's no body set, we need to reset the rich text record such that it is not autosaved. + public_send("#{name}=", nil) if public_send(name).body.blank? + end + + after_save do + rich_text = public_send(name) + + if rich_text.changed? && rich_text.body.present? + rich_text.save + elsif rich_text.persisted? && rich_text.body.blank? + rich_text.destroy + end + end end end end diff --git a/lib/action_text/content.rb b/lib/action_text/content.rb index c296896ac4..22b52cff1c 100644 --- a/lib/action_text/content.rb +++ b/lib/action_text/content.rb @@ -4,7 +4,7 @@ module ActionText attr_reader :fragment - delegate :blank?, :empty?, :html_safe, :present?, to: :to_s + delegate :blank?, :empty?, :html_safe, :present?, to: :to_html # Delegating to to_html to avoid including the layout def initialize(content = nil) @fragment = ActionText::Attachment.fragment_by_canonicalizing_attachments(content) -- cgit v1.2.3