Как проверить, что поле Rails rich_text_field (Action Text) пустое?

Я не могу найти это нигде - консоль показывает поле как nil но в действительности текст действия хранит содержимое, которое может быть "пустым".

MyModel.rich_text_field.nil? возвращает false независимо от того, является ли фактическое содержимое пустым или нет.

2 ответа

Решение

Вы можете проверить, не заполнено ли поле вашей модели:

MyModel.rich_text_field.blank?

Вот как я закончил обработку проверок для полей Action Text, чтобы определить, были ли они пустыми.

в моем posts_controller я убедился, что if @post.save в блоке response_to.

        # POST /posts or /posts.json
  def create
    @post = current_user.posts.new(post_params)

    respond_to do |format|
      if @post.save
        flash[:success] = "Post was successfully created."
        format.html { redirect_to @post }
        format.json { render :show, status: :created, location: @post }
      else
        format.html { render :new, status: :unprocessable_entity }
        format.json { render json: @post.errors, status: :unprocessable_entity }
      end
    end
  end

в моей модели Post я добавил аксессуар атрибута с настраиваемыми проверками.

      class Post < ApplicationRecord
  
  attr_accessor :body
  
  # Action Text, this attribute doesn't actually exist in the Post model
  # it exists in the action_text_rich_texts table                  
  has_rich_text :body

  # custom validation (Note the singular validate, not the pluralized validations)
  validate :post_body_cant_be_empty


  # custom model validation to ensure the post body that Action Text uses is not empty
   def post_body_cant_be_empty 
      if self.body.blank?
        self.errors.add(:body, "can't be empty") 
    end   
  end

end

теперь будет запущена настраиваемая проверка, чтобы проверить, является ли тело сообщения «Текст действия» пустым, и если это ошибка, будет отображаться пользователю при отправке формы.

Другие вопросы по тегам