---
# System prepended metadata

title: 使用 Rails內建的文字編輯器
tags: [ruby, rails]

---

# 使用 Rails內建的文字編輯器

###### tags: `rails`, `ruby`
環境:
> ruby 2.6.7
> 
> Rails 6.1.3.1
> 
> Ubuntu 20.04 LTS

資源連結:
[**Rails-Action Text Overview**](https://guides.rubyonrails.org/action_text_overview.html)

推到heroku無法正常顯示styles問題:
[**heroku Action Text 無法正常顯示**](https://stackoverflow.com/questions/64012746/action-text-trix-styles-doesnt-load-in-production-rails-6-heroku)

## :memo:

### Step 1: 使用yarn安裝文字編輯器

```ruby=
# 移動至Ubuntu
$ rails action_text:install

$ rails db:migrate

```

### Step 2: 移動至專案webpacker資料夾內,新增文字編輯器scss及import相關檔案

```ruby=
# 路徑:/appname/app/javascript/packs/application.js
require("trix")
require("@rails/actiontext")
import './application.scss'

# 路徑:/appname/app/javascript/packs/application.scss
@import "./actiontext.scss";

# 路徑:/appname/app/javascript/packs/新增(actiontext.scss)
@import "trix/dist/trix";
```


### Step 3: 移動想要使用文字編輯器的model增加相關欄位及顯示

```ruby=
# 路徑: app/models/message.rb

class Message < ApplicationRecord
  has_rich_text :content
end

# 路徑: app/views/messages/_form.html.erb

<%= form_with model: message do |form| %>
  <div class="field">
    <%= form.label :content %>
    <%= form.rich_text_area :content %>
  </div>
<% end %>
```

```ruby=
# Controller相關設置
class MessagesController < ApplicationController
  def create
    message = Message.create! params.require(:message).permit(:title, :content)
    redirect_to message
  end
end
```