Rails Generator Handles Action Text Fields
Rails Action Text enables rich text content editing via Basecamp's Trix editor. To associate rich text with an Active Record model, you typically use the has_rich_text method. However, Rails generators can now handle Action Text fields directly, making setup even easier.
Using Generators with Action Text
You can configure Action Text rich text fields using Rails model and scaffold generators by providing the rich_text field attribute:
Model Generator
$ bin/rails generate model Message content:rich_text
This command will:
- Create the
Messagemodel - Add
has_rich_text :contentto the model - Set up the necessary migrations
Scaffold Generator
$ bin/rails generate scaffold Post title:string body:rich_text
This creates:
- The model with
has_rich_text :body - Controllers with proper Action Text handling
- Views with the Trix editor configured
- Routes and migrations
Generated Model
The generator automatically adds the has_rich_text association:
class Message < ApplicationRecord
has_rich_text :content
end
Generated Views
The scaffold generator creates views with the Trix editor:
<!-- app/views/messages/_form.html.erb -->
<%= form_with(model: message) do |form| %>
<%= form.rich_text_area :content %>
<!-- Other fields -->
<% end %>
Migration
The generator creates the necessary migration for Action Text:
class CreateMessages < ActiveRecord::Migration[7.0]
def change
create_table :messages do |t|
t.timestamps
end
end
end
Note: Action Text tables (action_text_rich_texts and active_storage_*) are created separately when you run rails action_text:install.
Benefits
Using generators with Action Text fields provides:
- Consistency: Ensures proper setup across your application
- Time-saving: Automatically configures models and views
- Best practices: Follows Rails conventions for Action Text
- Less manual work: No need to manually add
has_rich_textor configure views
Example Usage
After generating, you can use Action Text in your controllers:
class MessagesController < ApplicationController
def create
@message = Message.new(message_params)
if @message.save
redirect_to @message
else
render :new
end
end
private
def message_params
params.require(:message).permit(:content)
end
end
Conclusion
Rails generators now handle Action Text fields seamlessly, making it easier than ever to add rich text editing to your Rails applications. This feature reduces boilerplate and ensures consistent Action Text setup across your models and views.