class Post < ApplicationRecord
...
# for validation only
attr_accessor :content
# action text
has_rich_text :content
...
validate :post_content_present
def post_content_present
errors.add(:content, "can't be empty") if message.blank?
end
...
end
It’s validate (without s). I’m using this with simple_form, it should work with plain forms too.
ok, it does work but it just says ‘Please review the problems below:’ but it’s missing ‘content can’t be blank.’ (that’s part of the error message that works for the regular text boxes).
I guess that rich text field isn’t wrapped to display error messages?
What is shown in the error message depends depends - simply spoken - on your code. How do you show errors in your form?
Plain rails 7.0 generator provides something like this (my model here is Person):
<%= form_with(model: person) do |form| %>
<% if person.errors.any? %>
<div style="color: red">
<h2><%= pluralize(person.errors.count, "error") %> prohibited this person from being saved:</h2>
<ul>
<% person.errors.each do |error| %>
<li><%= error.full_message %></li>
<% end %>
</ul>
</div>
<% end %>
It iterates over person.errors and shows each single error separate.
SimpleForm generates the following code:
<%= form.error_notification %>
<%= form.error_notification message: form.object.errors[:base].to_sentence if form.object.errors[:base].present? %>
so only errors[:base] is shown, not the errors for each attribute. With a working initializer for simple form it shows the errors for a single attribute below the input field and set the failing input field in red.
Without knowing your error display code, which may be different from those above, you can also put the error message in errors[:base]:
def post_content_present
errors.add(:base, "content can't be empty") if content.blank?
end
The example above has an error, please replace message.blank? with content.blank? (sorry, I#m not able to edit it).
Just for reference: with rails 7.0 it is not neccessary to do something fancy for validations on rich_text. Just standard validations works well:
class Post < ApplicationRecord
has_rich_text :content
validates_presence_of :content
...
end
I mixed up the form error display: blue is rails standard style from the generator, all in red is from the SimpleForm template generator. Both works fine.