Action Text
Action Text
Action Text brings rich text content and editing to Rails. It includes the Trix editor that handles everything from formatting to links to quotes to lists to embedded images and galleries. The rich text content generated by the Trix editor is saved in its own RichText model that’s associated with any existing Active Record model in the application. Any embedded images (or other attachments) are automatically stored using Active Storage and associated with the included RichText model.
Getting Started
At first we have to install rails action text.
1
rails action_text:install
Run the above command to add yarn package and copy over the necessary migration.
This will create the migration files for active storage and action text. So run
1
rails db:migrate
Now lets create a scaffold.
1
rails g scaffold Attraction name
Add a rich text field to the Post model
1
2
3
class Attraction < ApplicationRecord
has_rich_text :content
end
Then in the form add rich_text_area
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
= form_with(model: attraction, local: true) do |form|
- if attraction.errors.any?
#error_explanation
h2
= pluralize(attraction.errors.count, "error")
| prohibited this attraction from being saved:
ul
- attraction.errors.full_messages.each do |message|
li= message
.field
= form.label :name
= form.text_field :name
.field
= form.label :content
= form.rich_text_area :content
.actions
= form.submit
We also have to permit the content
in our posts_controller.rb
1
2
3
def attraction_params
params.require(:attraction).permit(:name, :content)
end
And finally display the sanitized rich text on a page:
1
= @attraction.content
To use the images, we must uncomment the gem image_processing
1
gem 'image_processing', '~> 1.2'
Snapshots
new form
new form with images inside Trix editor
show page when attraction is saved