1

I have a very simple action text model and form

class Course < ApplicationRecord 
  validates :title, presence: true
  has_rich_text :content
end

<%= form_with model: @course do |f| %>
  <%= f.text_field :title %>
  <%= f.rich_text_area :content %>
<% end %>

It's all working great but since the content field is optional is it possible to create a course model without creating action_text_rich_texts entries that are empty/blank? Even if the user only enters the title without any content it's currently creating them and there's a lot of unnecessary and empty action_text_rich_texts rows in the database

vince
  • 2,374
  • 4
  • 23
  • 39

3 Answers3

2

The way I handled this in my application is with a before_save callback that removes the ActionText::RichText database record if the body is blank.

This avoids polluting the controller and works on both create and update actions. The body attribute of the action_text attribute is still accessible even without a corresponding database record, because ActionText will instantiate a new object if the record cannot be found (which allows you to test for blank? in either scenario).

Try this:

class Course < ApplicationRecord 
  validates :title, presence: true
  has_rich_text :content
  before_save :clean_up_content

  private

  def clean_up_content
    self.content.destroy if self.content.body.blank?
  end
end
Eric Powell
  • 21
  • 1
  • 2
1

I'm not sure about anything built into Actiontext for this, but I would imagine you could handle this at the controller level.

The first thing I would try is to see if not setting anything to content prevents Rails from creating an associated record:

class CourseController
  def create
    # remove course_params[:content] if it's blank
    course_values = course_params[:content].blank? ? course_params.except(:content) : course_params

    Course.create(course_values)
    ...
  end
end
Chiperific
  • 4,428
  • 3
  • 21
  • 41
  • 1
    that works when creating a course without a content, *but* if a course already had a content and it is erased on an update it does not erase the content – vince Oct 29 '20 at 17:01
0

Extending Eric Powell's approach:

# app/models/concerns/do_not_save_blank_rich_text.rb

module DoNotSaveBlankRichText
  extend ActiveSupport::Concern

  included do
    before_validation :do_not_save_blank_rich_text
  end

  private

  def do_not_save_blank_rich_text
    rich_text_attributes = self.class.reflections.values.select do |reflection|
      reflection.options[:class_name] == "ActionText::RichText"
    end.map(&:name)
    rich_text_attributes.each do |rich_text_attribute|
      if self.public_send(rich_text_attribute) && self.public_send(rich_text_attribute).body.blank?
        self.public_send(rich_text_attribute).mark_for_destruction
      end
    end
  end
end

haroldus
  • 111
  • 1
  • 3