LoginSignup
2

More than 1 year has passed since last update.

[Rails] Action Text 導入

Posted at

Action Textとは?

Rails6から導入された新機能で、リッチテキストと呼ばれるモダンなエディター機能が使える。
action text.gif

今回はこのAction Textの導入方法のメモです。

実装

① 導入

imagemagickは画像変換するためのツール。
Action Textはエディター内で画像の挿入ができるので必要。

ターミナル
$ brew install imagemagick

Gemfileの以下の部分のコメントアウトを外してbundle install

Gemfile
gem 'image_processing', '~> 1.2'

ターミナルに以下をそれぞれ追加。

ターミナル
$ bundle exec rails action_text:install
ターミナル
$ bundle exec rails webpacker:install

ここまでできたら以下のようなmigrationファイルが追加されているのを確認して、migrationを実行。

db/migrate/20210622011818_create_action_text_tables.action_text.rb
class CreateActionTextTables < ActiveRecord::Migration[6.0]
  def change
    create_table :action_text_rich_texts do |t|
      t.string     :name, null: false
      t.text       :body, size: :long
      t.references :record, null: false, polymorphic: true, index: false

      t.timestamps

      t.index %i[record_type record_id name], name: 'index_action_text_rich_texts_uniqueness', unique: true
    end
  end
end

ターミナル
$ rails db:migrate

これで導入完了。

② カラムの削除

Action Textを使用したいmodel部分に以下を追加。
今回はEvent modelとします。

contentの部分はAction Textとして使用したいカラム名なので自分のカラムに合わせてください。
今回はcontentとします。

app/models/event.rb
has_rich_text :content

ちなみに、
既にcontentカラムを用意している場合Action Textでは独自のmigrationファイルに入力した値を保存してくれるでcontentカラム部分は不要になります。
なのでcontentカラムを消しておきましょう。

カラムの消し方はターミナルでカラム削除用のファイルを作成して、

ターミナル
$ rails g migration RemoveContentFromEvents

remove_columnで削除します。
remove_columnを使う際は最後にデータ型の指定を忘れずに!(textの部分)

db/migrate/20210622012137_remove_content_from_events.rb
class RemoveContentFromEvents < ActiveRecord::Migration[6.1]
  def change
    remove_column :events, :content, :text
  end
end

③ 反映

では最後にAction Textを使えるように反映していきましょう!

app/assets/stylesheets/actiontext.scssが追加されているのでそれをapplication.scssに追加。
trix-editorというのも追加してCSSを当てます。

app/assets/stylesheets/application.scss
@import 'actiontext';
@import 'trix/dist/trix.css';


trix-editor {
  min-height: 20em;
  max-height: 20em;
  overflow-y: auto;
}

最後にAction Textにしたい部分のviewsをrich_text_areaとすることで反映されます!

app/views/events/_form.html.haml
 = f.rich_text_area  :text, class: 'form-control'

これで完成!

おまけ

Action Textの内容を検索したい場合は以下の記事を参考にしてみてください!

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2