2
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

【Rails】Action Text 試してみた

Posted at

参考元

ゼロから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で書きました

2
0
0

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
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?