Qiita Teams that are logged in
You are not logged in to any team

Log in to Qiita Team
Community
OrganizationAdvent CalendarQiitadon (β)
Service
Qiita JobsQiita ZineQiita Blog
Help us understand the problem. What is going on with this article?

【Rails】Action Text 試してみた

More than 1 year has passed since last update.

参考元

ゼロから10分でブログが作れる!Rails6の新機能Action Textを試してみた
Ruby on Rails 6の主要な新機能・機能追加・変更点

作ってみる

$ rails  new blogApp --webpack

article モデル作成

$ rails g scaffold article title:string

Action Text導入

gem 'actiontext', github: 'kobaltz/actiontext', branch: 'archive', require: 'action_text'
gem 'image_processing'
$ bundle
$ rails action_text:install
$ rails db:migrate
app/views/layouts/application.html.erb
- <%= javascript_link_tag 'application', 'data-turbolinks-track': 'reload' %>
+ <%= javascript_pack_tag 'application', 'data-turbolinks-track': 'reload' %>

モデル編集

has_rich_textは独自メソッド

app/models/article.rb
class Article < ApplicationRecord
  has_rich_text :content
end

コントローラーを編集

app/controllers/articles_controller.rb
class ArticlesController < ApplicationController 
  before_action :set_article, only: [:show, :edit, :update, :destroy] |

  #省略

  private
    #省略

    def article_params
      params.require(:article).permit(:title, :content) #:contentを追加
    end
end

view編集

:app/views/articles/_form/html.erb
<%= form_with(model: article, local: true) do |form| %> |
  <% if article.errors.any? %> 
    <div id="error_explanation"> 
      <h2><%= pluralize(article.errors.count, "error") %> prohibited this article from being saved:</h2>
        <ul> 
          <% article.errors.full_messages.each do |message| %>
            <li><%= message %></li>
          <% end %>
        </ul>
    </div>
 <% end %>

  <div class="field"> 
     <%= form.label :title %> 
     <%= form.text_field :title %> 
  </div> 
  <!-- 追記 --> 
  <div class="field"> 
    <%= form.label :content %> 
    <%= form.rich_text_area :content %> 
  </div> 

  <div class="actions"> 
    <%= form.submit %> 
  </div> 
<% end %>

Screen Shot 0001-11-10 at 19.51.57.png

できた

注意点(私がはまりました)

slimで実装してるとリッチテキストエディターが実装できてもshow.html.slimだと
表示が変になります

Screen Shot 0001-11-10 at 19.54.29.png

こんな風になってしまいました。

まだslimがaction textのやり方に対応してないからここだけ仕方なくhtml.erbで書きました

hayulu
教育系IT企業でRails フロントエンドをやってました 今は自分でRailsアプリを作れるように勉強中
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away