mirror of
https://github.com/rails/rails.git
synced 2022-11-09 12:12:34 -05:00
Ensure blank rich text records aren't saved or required
This commit is contained in:
parent
0fd8ba6fff
commit
3431c0b3ee
4 changed files with 30 additions and 2 deletions
|
@ -6,6 +6,8 @@ class ActionText::RichText < ActiveRecord::Base
|
|||
belongs_to :record, polymorphic: true, touch: true
|
||||
has_many_attached :embeds
|
||||
|
||||
validate { errors.add(:body, "is missing") if body.blank? }
|
||||
|
||||
before_save do
|
||||
self.embeds = body.attachments.map(&:attachable)
|
||||
end
|
||||
|
|
|
@ -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
|
||||
|
|
|
@ -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)
|
||||
|
|
|
@ -7,6 +7,19 @@ module ActionText
|
|||
assert_equal "Hello world", message.content.body.to_plain_text
|
||||
end
|
||||
|
||||
test "creating a model with rich text content will not create a rich text record" do
|
||||
message = Message.create!(subject: "Greetings")
|
||||
assert message.content.body.nil?
|
||||
end
|
||||
|
||||
test "removing content removes the rich text record" do
|
||||
message = Message.create!(subject: "Greetings", content: "<h1>Hello world</h1>")
|
||||
|
||||
assert_difference -> { ActionText::RichText.all.count }, -1 do
|
||||
message.update!(content: "")
|
||||
end
|
||||
end
|
||||
|
||||
test "embed extraction" do
|
||||
blob = create_file_blob(filename: "racecar.jpg", content_type: "image/jpg")
|
||||
message = Message.create!(subject: "Greetings", content: ActionText::Content.new("Hello world").append_attachables(blob))
|
||||
|
|
Loading…
Reference in a new issue