Rails6 入門

Rails6 入門

目次

1 概要

2 リンク

3 初めてのプロジェクト作成

3.1 以下の操作を行っている動画


3.2 以前作成したDocker imageを動かす

docker run -it --rm -p 22:22 -p 3000:3000 -v /work/myrails:/home/user/C myrails
# or
./Start.sh

3.3 test01というプロジェクト開始

  • プロジェクトを作成し、test01内に移動
rails new test01
cd test01
bundle install

3.4 railsサーバーを起動して、ブラウザで確認

  • 以下のコマンドを実行し、ブラウザでhttp://localhost:3000を開く。ウエルカムページが表示される。
rails server -b 0.0.0.0

3.5 この章のまとめ

  • 空のプロジェクトを作成し、ブラウザで確認した

4 scaffoldを利用したモデルの作成

4.1 以下の操作を行っている動画


4.2 以前作成したDocker imageを動かす

docker run -it --rm -p 22:22 -p 3000:3000 -v /work/myrails:/home/user/C myrails
# or
./Start.sh

4.3 test02というプロジェクト開始

  • プロジェクトを作成し、test02内に移動
rails new test02
cd test02
bundle install

4.4 test02で、scaffoldコマンドを利用して、モデルを作成

  • unit
rails generate scaffold  Unit name:string strength:decimal hitPoints:decimal agility:decimal

4.5 railsサーバーを起動して、ブラウザで確認

rails server -b 0.0.0.0
  • 追加したり、変更したり、削除したりしてみる

4.6 この章のまとめ

  • 楽々自動コマンドscaffoldを利用して、モデルと、それを操作できるインターフェイスを自動生成
  • 生成した物を試してみる

5 scaffoldのカスタマイズ

  • i18n_generatorsを利用した方法の解説ページのとおりにやっても、Railsのバージョンが古いためか、上手く日本語化できなかったので、Rails6でも日本語化できるようにカスタマイズしてみた。
  • 多分もっと良いカスタマイズ方法あるとは思うが、とりあえず日本語化には成功した設定方法になります。

5.1 以下の操作を行っている動画


5.2 以前作成したDocker imageを動かす

docker run -it --rm -p 22:22 -p 3000:3000 -v /work/myrails:/home/user/C myrails
# or
./Start.sh

5.3 test03というプロジェクト開始

  • プロジェクトを作成し、test02内に移動
rails new test03
cd test03
bundle install

5.4 gitの初期化のファイル init_git.sh を用意

  • 以下の内容の ../init_git.sh を準備
#!/bin/sh
git config --global user.name "NM Max"
git config --global user.email xxx@xxx.xx
  • 実行権限を与える
chmod +x ../init_git.sh
  • 実行
../init_git.sh

5.5 gitでバージョン管理する為の準備

  • ワーキングツリー空のコミットを最初に
  • プロジェクト作成直後のコミットを次に
git init
git commit --allow-empty -m "first commit"
git add -A
git commit --allow-empty -m "プロジェクト作成直後"

5.6 scaffold日本語化に関するパッケージをGemfileに追加

  • 以下を追加
gem 'i18n_generators'
gem 'rails-i18n'
  • 以下を実行
bundle install

5.7 日本語関係の設定をconfig/application.rbに

require_relative 'boot'

require 'rails/all'

# Require the gems listed in Gemfile, including any gems
# you've limited to :test, :development, or :production.
Bundler.require(*Rails.groups)

module Test02
  class Application < Rails::Application
    # Initialize configuration defaults for originally generated Rails version.
    config.load_defaults 6.0

    config.time_zone = 'Asia/Tokyo'
    config.i18n.load_path += Dir[Rails.root.join('my', 'locales', '*.{rb,yml}')]
    config.i18n.default_locale = :ja 

    # Settings in config/environments/* take precedence over those specified here.
    # Application configuration can go into files in config/initializers
    # -- all .rb files in that directory are automatically loaded after loading
    # the framework and any gems in your application.
  end
end

5.8 scaffold用のカスタマイズテンプレートを用意

  • rake rails:templates:copy でエラーになるため、ベースのテンプレートファイルをマニュアルでコピー(Rails6でもできるのかな?他のサイトの方法?)して修正

5.8.1 以下のコマンドでscaffoldオリジナルのテンプレートファイルを探す

find /usr/local/bundle/ | grep scaf

5.8.2 scaffoldオリジナルのテンプレートファイルをlib/templates/erb/scaffold/にコピー

mkdir -p lib/templates/erb/scaffold/
cp /usr/local/bundle/gems/railties-6.0.2.1/lib/rails/generators/erb/scaffold/templates/* lib/templates/erb/scaffold/

5.8.3 lib/templates/erb/scaffold/edit.html.erb.tt を以下に修正

<h1><%%= t('usual.edit') %> <%%= <%= class_name %>.model_name.human %></h1>

<%%= render 'form', <%= singular_table_name %>: @<%= singular_table_name %> %>

<%%= link_to t('usual.show'), @<%= singular_table_name %> %> |
<%%= link_to t('usual.back'), <%= index_helper %>_path %>

5.8.4 lib/templates/erb/scaffold/index.html.erb.tt を以下に修正

<p id="notice"><%%= notice %></p>

<h1><%%= <%= class_name %>.model_name.human %></h1>

<table>
  <thead>
    <tr>
<% attributes.reject(&:password_digest?).each do |attribute| -%>
  <th><%%= <%= class_name %>.human_attribute_name( :<%= attribute.name %> ) %></th>
<% end -%>
      <th colspan="3"></th>
    </tr>
  </thead>

  <tbody>
    <%% @<%= plural_table_name %>.each do |<%= singular_table_name %>| %>
      <tr>
<% attributes.reject(&:password_digest?).each do |attribute| -%>
	<td><%%= <%= singular_table_name %>.<%= attribute.column_name %> %></td>
<% end -%>
	<td><%%= link_to t('usual.show'), <%= model_resource_name %> %></td>
	<td><%%= link_to t('usual.edit'), edit_<%= singular_route_name %>_path(<%= singular_table_name %>) %></td>
	<td><%%= link_to t('usual.delete'), <%= model_resource_name %>, method: :delete, data: { confirm: t('usual.confirm.delete') } %></td>
      </tr>
    <%% end %>
  </tbody>
</table>

<br>

<%%= link_to "#{t('usual.new')} <%= singular_table_name.titleize %>", new_<%= singular_route_name %>_path %>

5.8.5 lib/templates/erb/scaffold/new.html.erb.tt を以下に修正

<h1><%%= t('usual.new') %><%%= <%= class_name %>.model_name.human %></h1>

<%%= render 'form', <%= singular_table_name %>: @<%= singular_table_name %> %>

<%%= link_to t('usual.back'), <%= index_helper %>_path %>

5.8.6 lib/templates/erb/scaffold/show.html.erb.tt を以下に修正

<p id="notice"><%%= notice %></p>

<% attributes.reject(&:password_digest?).each do |attribute| -%>
<p>
  <strong>
    <%%= label :<%= singular_table_name %>, :<%= attribute.name %> %>:
  </strong>
<% if attribute.attachment? -%>
  <%%= link_to @<%= singular_table_name %>.<%= attribute.column_name %>.filename, @<%= singular_table_name %>.<%= attribute.column_name %> if @<%= singular_table_name %>.<%= attribute.column_name %>.attached? %>
<% elsif attribute.attachments? -%>
  <%% @<%= singular_table_name %>.<%= attribute.column_name %>.each do |<%= attribute.singular_name %>| %>
    <div><%%= link_to <%= attribute.singular_name %>.filename, <%= attribute.singular_name %> %></div>
  <%% end %>
<% else -%>
  <%%= @<%= singular_table_name %>.<%= attribute.column_name %> %>
<% end -%>
</p>

<% end -%>
<%%= link_to t('usual.edit'), edit_<%= singular_table_name %>_path(@<%= singular_table_name %>) %> |
<%%= link_to t('usual.back'), <%= index_helper %>_path %>

5.9 config/locales/usual_ja.yml を以下で作成

ja:
  usual:
    index: 一覧
    show: 詳細
    new: 新規
    edit: 編集
    delete: 削除
    confirm:
      delete: 削除しますが、よろしいですか?
    back: 戻る
    create:
      success: "%{name}を作成しました"
      failed: 作成に失敗しました
    update:
      success: "%{name}を更新しました"
      failed: 更新に失敗しました
    destroy:
      success: "%{name}を削除しました"
      failed: 削除に失敗しました
    form:
      error_explanation:
        title: "%{count}件のエラーがあります"

5.10 config/locales/usual_en.yml を以下で作成

ja:
  usual:
    index: index
    show: show
    new: new
    edit: edit
    delete: delete
    confirm:
      delete: Are you sure?
    back: back
    create:
      success: "%{name} was created successfully"
      failed: Creation failed
    update:
      success: "%{name} was updated successfully"
      failed: Update failed
    destroy:
      success: "%{name} was deleted successfully"
      failed: Delete failed
    form:
      error_explanation:
        title: "There are %{count} errors"

5.11 test03で、scaffoldコマンドを利用して、モデルを作成

  • Unitモデル作成
rails generate scaffold  Unit name:string strength:decimal hitPoints:decimal agility:decimal
rails db:migrate
  • 日本語用ファイル生成
rails g i18n ja
  • コミットしておく
git add -A
git commit --allow-empty -m "Unitモデル作成"

5.12 railsサーバーを起動して、ブラウザで確認

rails server -b 0.0.0.0
  • 追加したり、変更したり、削除したりしてみる

5.13 この章のまとめ

  • 楽々自動コマンドscaffoldをカスタマイズして、メニューの日本語化の一例

6 Action Textを試してみる

  • この章から新しいDocker Imageを利用していきます。(改良バージョン 作り方https://www.youtube.com/watch?v=naQWBg6G1wM)
  • 画像とかを複数いれたリッチテキストを扱える新機能Action Textを使ってみました。

6.1 以前作成したDocker imageを動かす

docker run -it --rm -p 22:22 -p 3000:3000 -v /work/myrails:/home/user/C myrails3
# or
./Start.sh

6.2 作業手順

6.2.1 起動後、改良バージョンで標準で含まれているtest000プロジェクトに移動

cd test000

6.2.2 Gemfileに以下を追加

gem 'mini_magick'
gem 'image_processing'

6.2.3 bundle install を実行

bundle install 

6.2.4 rails action_text:install を実行

rails action_text:install
rails db:migrate

6.2.5 t0モデルをscaffoldで作成

rails g scaffold t0 name:string

6.2.6 ./app/views/active_storage/blobs/_blob.html.erb を以下に修正

  • 以下が修正後
  • mini_magickの指定の方法がこれらしい
... 省略
  <%= image_tag blob.representation(resize: local_assigns[:in_gallery] ? "800x600" : "1024x768" ) %>
... 省略

6.2.7 ./app/models/t0.rb を以下に修正

class T0 < ApplicationRecord
  has_rich_text :content
end

6.2.8 ./app/controllers/t0s_controller.rb を以下に修正

  • :content を追加
... 省略
    # Only allow a list of trusted parameters through.
    def t0_params
      params.require(:t0).permit(:name,:content)
    end
end

6.2.9 ./app/views/t0s/_form.html.erb を以下に修正

<%= form_with(model: t0, local: true) do |form| %>
  <% if t0.errors.any? %>
    <div id="error_explanation">
      <h2><%= pluralize(t0.errors.count, "error") %> prohibited this t0 from being saved:</h2>

      <ul>
        <% t0.errors.full_messages.each do |message| %>
          <li><%= message %></li>
        <% end %>
      </ul>
    </div>
  <% end %>

  <div class="field">
    <%= form.label :name %>
    <%= form.text_field :name %>
  </div>

  <div class="field">
    <%= form.label :content %>
    <%= form.rich_text_area :content %>
  </div>

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

6.2.10 ./app/views/t0s/show.html.erb を以下に修正

<p id="notice"><%= notice %></p>

<p>
  <strong>Name:</strong>
  <%= @t0.name %>
</p>
<p>
  <strong>Content:</strong>
  <%= @t0.content %>
</p>

<%= link_to 'Edit', edit_t0_path(@t0) %> |
<%= link_to 'Back', t0s_path %>

6.2.11 migrate

rails db:migrate

6.2.12 動作確認

rails server -b 0.0.0.0

6.3 この章のまとめ

  • Rails 6から標準装備になった、Action Textを試してみた
  • こんなのが非常に簡単に作れちゃうRails凄い!

7 Action Textを試してみる2

  • Docker Imageを利用して動かします。(改良バージョン 作り方https://www.youtube.com/watch?v=naQWBg6G1wM)
  • 画像とかを複数いれたリッチテキストを扱える新機能Action Textを使ってみました。
  • 前章と同じだけど、mini_magickではなく、image_processingをGemfileに、そうするとblobの修正不要でした。

7.1 以下の操作を行っている動画


7.2 以前作成したDocker imageを動かす

docker run -it --rm -p 22:22 -p 3000:3000 -v /work/myrails:/home/user/C myrails3
# or
./Start.sh

7.3 作業手順

7.3.1 起動後、改良バージョンで標準で含まれているtest000プロジェクトに移動

cd test000

7.3.2 Gemfileに以下を追加

  • 前の章と違い、Gemfileにmini_magickをいれません。
  • rails action_text:install も行わない
  • ./app/views/active_storage/blobs/_blob.html.erb も修正しません。
gem 'image_processing'

7.3.3 bundle install を実行

  • 前の章と同じ
bundle install 

7.3.4 t0モデルをscaffoldで作成

  • 前の章と同じ
rails g scaffold t0 name:string

7.3.5 ./app/models/t0.rb を以下に修正

  • 前の章と同じ
class T0 < ApplicationRecord
  has_rich_text :content
end

7.3.6 ./app/controllers/t0s_controller.rb を以下に修正

  • 前の章と同じ
  • :content を追加
... 省略
    # Only allow a list of trusted parameters through.
    def t0_params
      params.require(:t0).permit(:name,:content)
    end
end

7.3.7 ./app/views/t0s/_form.html.erb を以下に修正

  • 前の章と同じ
<%= form_with(model: t0, local: true) do |form| %>
  <% if t0.errors.any? %>
    <div id="error_explanation">
      <h2><%= pluralize(t0.errors.count, "error") %> prohibited this t0 from being saved:</h2>

      <ul>
        <% t0.errors.full_messages.each do |message| %>
          <li><%= message %></li>
        <% end %>
      </ul>
    </div>
  <% end %>

  <div class="field">
    <%= form.label :name %>
    <%= form.text_field :name %>
  </div>

  <div class="field">
    <%= form.label :content %>
    <%= form.rich_text_area :content %>
  </div>

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

7.3.8 ./app/views/t0s/show.html.erb を以下に修正

  • 前の章と同じ
<p id="notice"><%= notice %></p>

<p>
  <strong>Name:</strong>
  <%= @t0.name %>
</p>
<p>
  <strong>Content:</strong>
  <%= @t0.content %>
</p>

<%= link_to 'Edit', edit_t0_path(@t0) %> |
<%= link_to 'Back', t0s_path %>

7.3.9 migrate

rails db:migrate

7.3.10 動作確認

rails server -b 0.0.0.0

7.4 この章のまとめ

  • mini_magickではなく、image_processingがデフォルトになってた情報をみて、試してみたら、blobsの修正なくいけた
  • 前章より修正部分少なく、より豊富な機能を実現(画像おそらく固定サイズではなくなる)

8 ちゃちゃっと日記を作ってみる

  • Action Textを利用して、ちゃちゃっと日記を作ってみる
  • rails-i18n,i18n_generatorsを使って、日本語化
  • 操作画面はrails_adminを活用して作成

8.1 以下の操作を行っている動画


8.2 以前作成したDocker imageを動かす

docker run -it --rm -p 22:22 -p 3000:3000 -v /work/myrails:/home/user/C myrails3
# or
./Start.sh

8.3 作業手順

8.3.1 起動後、改良バージョンで標準で含まれているtest000プロジェクトに移動

cd test000

8.3.2 Gemfileに以下を追加

  • 前の章と違い、Gemfileにmini_magickをいれません。
  • rails action_text:install も行わない
  • ./app/views/active_storage/blobs/_blob.html.erb も修正しません。
gem 'image_processing'
gem 'rails_admin'
gem 'rails-i18n', '~> 6.0.0' # For 6.0.0 or higher
gem 'i18n_generators'

8.3.3 bundle install を実行

  • 前の章と同じ
bundle install 

8.3.4 dianryモデルを作成

rails g scaffold dialy::post date:datetime title:string

8.3.5 ./app/models/dialy/post.rb を以下に修正

class Dialy::Post < ApplicationRecord
  has_rich_text :content
end

8.3.6 ./app/controllers/dialy/posts_controller.rb を以下に修正

  • :content を追加
... 省略
    # Only allow a list of trusted parameters through.
    def dialy_post_params
      params.require(:dialy_post).permit(:date, :title, :content)
    end
end

8.3.7 app/views/dialy/posts/_form.html.erb を以下に修正

  • scaffoldで作成したものを使わないなら不要
  • 以下に:content用の部分を追加
... 省略
  <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 %>

8.3.8 app/views/dialy/posts/show.html.erb を以下に修正

  • scaffoldで作成したものを使わないなら不要
  • 以下に:content用の部分を追加
<p id="notice"><%= notice %></p>

<p>
  <strong>Date:</strong>
  <%= @dialy_post.date %>
</p>

<p>
  <strong>Title:</strong>
  <%= @dialy_post.title %>
</p>

<p>
  <strong>Content:</strong>
  <%= @dialy_post.content %>
</p>

<%= link_to 'Edit', edit_dialy_post_path(@dialy_post) %> |
<%= link_to 'Back', dialy_posts_path %>

8.3.9 日本語設定用ファイルをconfig/locales/に入れる

wget https://gist.githubusercontent.com/mshibuya/1662352/raw/3f001f00f440af613d7d307cbf2f07c3babe2068/rails_admin.ja.yml
#wget https://raw.githubusercontent.com/svenfuchs/rails-i18n/master/rails/locale/ja.yml
mv -i *ja.yml config/locales/

8.3.10 config/application.rbを修正

  • 日本語関係、タイムゾーン設定
...省略
    config.time_zone = 'Tokyo'
    config.active_record.default_timezone = :local
    config.i18n.default_locale = :ja
    config.i18n.load_path += Dir[Rails.root.join('config', 'locales', '**', '*.{rb,yml}').to_s]
  end
end

8.3.11 rails_adminをインストール

  • 途中で聞かれる名前は rails_admin と入力しエンター
rails g rails_admin:install

8.3.12 i18n_generatorsで日本語用ファイル生成

  • config/locales/translation_ja.yml を確認
rails db:migrate
rails g i18n ja
# rails g i18n_locale ja
# rails g i18n_translation ja

8.4 railsサーバーを起動して、ブラウザで確認

rails server -b 0.0.0.0

8.5 この章のまとめ

  • 日記を作ってみた
  • 操作画面をrails_adminでも作成してみたが、デフォルト設定だと、画像関係追加のボタンもなく、正常に画像が表示されない(調査継続、上手くいく方法みつけたらまた文書と動画にします)

9 一旦scaffoldで生成したモデルを破壊し、作り直す手順

  • 普通に再度scaffoldしなおすと、The name ‘モデル名’ is either already used in your application or reserved by Ruby on Rails. Please choose an alternative and run this generator again と怒られる
  • rails destroy scaffold モデル名してからやり直すと、エラーなく再度生成可能

9.1 以下の操作を行っている動画


9.2 以前作成したDocker imageを動かす

docker run -it --rm -p 22:22 -p 3000:3000 -v /work/myrails:/home/user/C myrails3
# or
./Start.sh

9.3 作業手順

9.3.1 起動後、改良バージョンで標準で含まれているtest000プロジェクトに移動

cd test000

9.3.2 bundle install を実行

bundle install 

9.3.3 dianryモデルを作成

rails g scaffold Dialy::Post date:datetime title:string
  • 再度同じ命令を実行するとエラーになる(以下が例)
Running via Spring preloader in process 1124
      invoke  active_record
The name 'Dialy::Post' is either already used in your application or reserved by Ruby on Rails. Please choose an alternative and run this generator again.

9.3.4 dianryモデルを破壊

rails destroy scaffold dialy::post
  • 上を実行してから以下を実行
rails g scaffold dialy::post date:datetime title:string
  • 成功しました!

9.4 この章のまとめ

  • 一旦scaffoldで生成したモデルを破壊し、作り直す手順
    • (rails destroy scaffold モデル名 を実行してから再度生成コマンド実行)

10 mailアドレスでログイン出来る機能をつけてみる(devise)

  • https://github.com/heartcombo/devise
  • rails-i18n,i18n_generatorsを使って、日本語化
  • 最低限の機能のみ(確認メール無し)
  • 前やった日記アプリを改造して行います。
  • 以下の手順は日記アプリを作る手順も含まれています。

10.1 以下の操作を行っている動画


10.2 以前作成したDocker imageを動かす

docker run -it --rm -p 22:22 -p 3000:3000 -v /work/myrails:/home/user/C myrails3
# or
./Start.sh

10.3 作業手順

10.3.1 起動後、改良バージョンで標準で含まれているtest000プロジェクトに移動

cd test000

10.3.2 Gemfileに以下を追加

  • 前の章と違い、Gemfileにmini_magickをいれません。
  • rails action_text:install も行わない
  • ./app/views/active_storage/blobs/_blob.html.erb も修正しません。
gem 'image_processing'
gem 'rails_admin'
gem 'rails-i18n', '~> 6.0.0' # For 6.0.0 or higher
gem 'i18n_generators'
gem 'devise'

10.3.3 bundle install を実行

  • 前の章と同じ
bundle install 

10.3.4 dianryモデルを作成

rails g scaffold dialy::post date:datetime title:string

10.3.5 ./app/models/dialy/post.rb を以下に修正

class Dialy::Post < ApplicationRecord
  has_rich_text :content
end

10.3.6 ./app/controllers/dialy/posts_controller.rb を以下に修正

  • :content を追加
... 省略
    # Only allow a list of trusted parameters through.
    def dialy_post_params
      params.require(:dialy_post).permit(:date, :title, :content)
    end
end

10.3.7 app/views/dialy/posts/_form.html.erb を以下に修正

  • scaffoldで作成したものを使わないなら不要
  • 以下に:content用の部分を追加
... 省略
  <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 %>

10.3.8 app/views/dialy/posts/show.html.erb を以下に修正

  • scaffoldで作成したものを使わないなら不要
  • 以下に:content用の部分を追加
<p id="notice"><%= notice %></p>

<p>
  <strong>Date:</strong>
  <%= @dialy_post.date %>
</p>

<p>
  <strong>Title:</strong>
  <%= @dialy_post.title %>
</p>

<p>
  <strong>Content:</strong>
  <%= @dialy_post.content %>
</p>

<%= link_to 'Edit', edit_dialy_post_path(@dialy_post) %> |
<%= link_to 'Back', dialy_posts_path %>

10.3.9 日本語設定用ファイルをconfig/locales/に入れる

wget https://gist.githubusercontent.com/mshibuya/1662352/raw/3f001f00f440af613d7d307cbf2f07c3babe2068/rails_admin.ja.yml
#wget https://raw.githubusercontent.com/svenfuchs/rails-i18n/master/rails/locale/ja.yml
mv -i *ja.yml config/locales/

10.3.10 config/application.rbを修正

  • 日本語関係、タイムゾーン設定
...省略
    config.time_zone = 'Tokyo'
    config.active_record.default_timezone = :local
    config.i18n.default_locale = :ja
    config.i18n.load_path += Dir[Rails.root.join('config', 'locales', '**', '*.{rb,yml}').to_s]
  end
end

10.3.11 i18n_generatorsで日本語用ファイル生成

  • config/locales/translation_ja.yml を確認
rails db:migrate
rails g i18n ja
# rails g i18n_locale ja
# rails g i18n_translation ja

10.4 railsサーバーを起動して、ブラウザで確認

rails server -b 0.0.0.0

10.4.1 deviseのインストール


  1. rails generate devise:install
    bundle exec rails g devise:views
    rails generate devise User
    rails db:migrate
    
  2. app/controllers/application_controller.rb に以下に
    class ApplicationController < ActionController::Base
      before_action :authenticate_user!
    end
    
  3. config/routes.rbに以下を追加
    devise_scope :user do
      get 'sign_in', to: 'devise/sessions#new'
      get 'sign_out', to: 'devise/sessions#destroy'
    end
    

10.5 railsサーバーを起動して、ブラウザで確認2

rails server -b 0.0.0.0

10.6 この章のまとめ

  • deviseパッケージを利用してメールアドレスでログイン出来る機能を追加
  • 確認メールを行う設定等は今後にやってみたいと考えてます

11 Rails6 + Administrate(管理画面生成)+ Action Text

11.1 以下の操作を行っている動画


11.2 以前作成したDocker imageを動かす

docker run -it --rm -p 22:22 -p 3000:3000 -v /work/myrails:/home/user/C myrails3
# or
./Start.sh

11.3 作業手順

11.3.1 起動後、前の章のプロジェクトディレクトリを作業用のディレクトリにコピーし、作成したディレクトリ内にはいる

  • 前の章のプロジェクトディレクトリをtest000-2-adminstrateにコピー
  • 使い慣れたホスト側のツールを使ってもOK
  • プロジェクト内部に移動し、必用なパッケージインストール
mkdir -p C/Youtube/000
cd C/Youtube/000
cp -r ~/test000 test000-2-adminstrate
cd test000-2-adminstrate
bundle install

11.3.2 Gitの初期設定

  • Gitの初期設定、名前を NM Max ,メールを架空の xxx@xxx.xx にしている、適切な名前とメールアドレスに
git config --global user.name "NM Max"
git config --global user.email xxx@xxx.xx
  • 最初のコミット(空)
git init
git commit --allow-empty -m "first commit"
  • 最初のコミット
git add -A
git commit -m "プロジェクト生成直後"

11.3.3 MyPostモデル追加

rails g scaffold MyPost title:string
rails db:migrate
  • gitでコミットしておく
git add -A
git commit -m "MyPost生成直後"

11.3.4 ./app/models/my_post.rb を以下に修正

class MyPost < ApplicationRecord
  has_rich_text :content
end

11.3.5 ./app/controllers/my_posts_controller.rb を以下に修正

  • :content を追加
... 省略
    # Only allow a list of trusted parameters through.
    def my_post_params
      params.require(:my_post).permit(:title, :content)
    end
end

11.3.6 ./app/views/my_posts/show.html.erb を以下に修正

<p id="notice"><%= notice %></p>

<p>
  <strong>Title:</strong>
  <%= @my_post.title %>
</p>

<p>
  <strong>Content:</strong>
  <%= @my_post.content %>
</p>

<%= link_to 'Edit', edit_my_post_path(@my_post) %> |
<%= link_to 'Back', my_posts_path %>

11.3.7 app/views/my_posts/_form.html.erb を以下に変更

<%= form_with(model: my_post, local: true) do |form| %>
  <% if my_post.errors.any? %>
    <div id="error_explanation">
      <h2><%= pluralize(my_post.errors.count, "error") %> prohibited this my_post from being saved:</h2>

      <ul>
	<% my_post.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 %>

11.3.8 Gemfileに 以下を追加

gem 'image_processing'
  • 以下を実行
bundle install
  • gitでコミットしておく
git add -A
git commit -m "MyPost設定"

11.4 railsサーバーを起動して、ブラウザで確認

rails server -b 0.0.0.0

11.4.1 Administrateを入れる

  1. Gemfileに 以下を追加
    # gem 'image_processing'
    # gem 'rails_admin'
    gem 'rails-i18n', '~> 6.0.0' # For 6.0.0 or higher
    gem 'i18n_generators'
    gem 'devise'
    
    gem "administrate" 
    gem 'administrate-field-active_storage'
    gem 'mini_magick'
    gem 'administrate-field-trix'
    gem 'trix-rails', require: 'trix'
    
    bundle install
    rails generate administrate:install
    rails g administrate:field rich_text_area
    #rails generate administrate:assets
    

11.4.2 ./app/views/fields/rich_text_area_field/_form.html.erb を以下に変更

<div class="field-unit__label">
  <%= f.label field.attribute %>
</div>
<div class="field-unit__field">
  <%= f.rich_text_area(field.attribute) %>
</div>

11.4.3 app/assets/config/manifest.js に以下を追加

//= link administrate/application.css
//= link administrate/application.js
//= link administrate-field-trix/application.css

11.4.4 https://github.com/thoughtbot/administrate/wiki/Rails-6-&-Webpacker に従い修正

  1. yarn add flatpickr を実行
    yarn add flatpickr
    
  2. app/javascript/packs/administrate.js を作成
    // This file is automatically compiled by Webpack, along with any other files
    // present in this directory. You're encouraged to place your actual application logic in
    // a relevant structure within app/javascript and only use these pack files to reference
    // that code so it'll be compiled.
    
    require("@rails/ujs").start()
    require("turbolinks").start()
    
    // The next line you only need if you want ActiveStorage support
    require("@rails/activestorage").start()
    
    // The next line you only need if you need channels in administrate
    require("channels")
    
    // The next two lines you only need if you want ActionText support
    require("trix")
    require("@rails/actiontext")
    
    require("../administrate/index")
    
  3. app/javascript/administrate/index.js を作成
    • デイレクトリ作成
    mkdir -p app/javascript/administrate
    
    • app/javascript/administrate/index.js を以下で作成
    import '../components/table'
    import '../components/date_time_picker'
    
  4. app/javascript/components/date_time_picker.js を作成
    mkdir -p app/javascript/components
    
    • 以下の内容の app/javascript/components/date_time_picker.js を作成
    import flatpickr from 'flatpickr'
    
    function bindDateTimePickers() {
      [...document.querySelectorAll('[data-type="time"]')].forEach((time) => {
        flatpickr(time, {
          enableTime: true,
          enableSeconds: true,
          noCalendar: true,
          altInput: true,
          altFormat: ' h:i:S K',
          dateFormat: 'H:i:S' // H:i
        })
      });
    
      [...document.querySelectorAll('[data-type="datetime"]')].forEach((time) => {
        flatpickr(time, {
          enableTime: true,
          altInput: true,
          altFormat: 'F J (D), Y - h:i:S K',
          dateFormat: 'Z' // Y-m-d H:i
        })
      })
    }
    
    document.addEventListener("turbolinks:load", function () {
      bindDateTimePickers()
    })
    
  5. app/javascript/components/table.js を作成
    mkdir -p app/javascript/components
    
    • 以下の内容の app/javascript/components/table.js を作成
    function bindTableLinks() {
      const keycodes = { space: 32, enter: 13 }
    
      function visitDataUrl(event) {
        /** @type {HTMLTableRowElement} */
        const target = event.target.classList.contains("js-table-row")
          ? event.target
          : event.target.closest('.js-table-row')
    
        if (!target) {
          return
        }
    
        if (event.type === "click" ||
            event.keyCode === keycodes.space ||
            event.keyCode === keycodes.enter) {
    
          if (event.target.href) {
            return
          }
    
          const dataUrl = target.getAttribute("data-url")
          const selection = window.getSelection().toString()
          if (selection.length === 0 && dataUrl) {
            const delegate = target.querySelector(`[href="${dataUrl}"]`)
            if (delegate) {
              delegate.click()
            } else {
              window.location = dataUrl
            }
          }
        }
      }
    
      const tables = [...document.getElementsByTagName("table")]
      tables.forEach(
        /** @type {HTMLTableElement} */ (table) => {
        table.addEventListener("click", visitDataUrl)
        table.addEventListener("keydown", visitDataUrl)
      })
    }
    
    document.addEventListener("turbolinks:load", function() {
      bindTableLinks()
    })
    
  6. app/views/layouts/admin/application.html.erb を作成
    mkdir -p app/views/layouts/admin/
    
    • 以下の内容の app/views/layouts/admin/application.html.erb を作成
    <%#
    # Application Layout
    
    This view template is used as the layout
    for every page that Administrate generates.
    
    By default, it renders:
    - Navigation
    - Content for a search bar
      (if provided by a `content_for` block in a nested page)
    - Flashes
    - Links to stylesheets and JavaScripts
    %>
    
    <!DOCTYPE html>
    <html lang="<%= I18n.locale %>">
      <head>
        <meta charset="utf-8">
        <meta name="robots" content="noodp, noydir, index, follow">
        <meta name="viewport" content="initial-scale=1">
        <title>
          <%= content_for(:title) || 'Dashboard' %> - <%= Rails.application.class.module_parent_name.titlecase %>
        </title>
        <%= javascript_pack_tag 'administrate', 'data-turbolinks-track': 'reload' %>
    
        <%= render "stylesheet" %>
        <%= csrf_meta_tags %>
    
    
        <meta name="turbolinks-root" content="/admin">
      </head>
      <body>
        <div class="app-container">
          <%= render "navigation" -%>
    
          <main class="main-content" role="main">
    	<%= render "flashes" -%>
    	<%= yield %>
          </main>
        </div>
    
        <div style="display: none; width: 0; height: 0; overflow: hidden; position: absolute">
          <%= render "icons" %>
        </div>
        <%= render "javascript" %>
      </body>
    </html>
    
  7. app/views/admin/application/_javascript.html.erb を作成
    mkdir -p app/views/admin/application/
    
    • 以下の内容の app/views/admin/application/_javascript.html.erb を作成
    <%#
    # Javascript Partial
    
    This partial imports the necessary javascript on each page.
    By default, it includes the application JS,
    but each page can define additional JS sources
    by providing a `content_for(:javascript)` block.
    
    Administrate::Engine.javascripts.each do |js_path|
     <= echo javascript_include_tag js_path
    <% end
    %>
    
    <%= yield :javascript %>
    
    <% if Rails.env.test? %>
      <%= javascript_tag do %>
        $.fx.off = true;
        $.ajaxSetup({ async: false });
      <% end %>
    <% end %>
    
  8. app/assets/stylesheets/administrate/application.scss を作成
    mkdir -p app/assets/stylesheets/administrate/
    
    • 以下の内容の app/assets/stylesheets/administrate/application.scss を作成
    @charset "utf-8";
    
    @import "administrate/reset/normalize";
    
    @import "administrate/library/clearfix";
    @import "administrate/library/data-label";
    @import "administrate/library/variables";
    
    @import "administrate/base/forms";
    @import "administrate/base/layout";
    @import "administrate/base/lists";
    @import "administrate/base/tables";
    @import "administrate/base/typography";
    
    @import "administrate/components/app-container";
    @import "administrate/components/attributes";
    @import "administrate/components/buttons";
    @import "administrate/components/cells";
    @import "administrate/components/field-unit";
    @import "administrate/components/flashes";
    @import "administrate/components/form-actions";
    @import "administrate/components/main-content";
    @import "administrate/components/navigation";
    @import "administrate/components/pagination";
    @import "administrate/components/search";
    
    @import "administrate/utilities/text-color";
    
    @import "trix/dist/trix";
    
    // We need to override trix.css’s image gallery styles to accommodate the
    // <action-text-attachment> element we wrap around attachments. Otherwise,
    // images in galleries will be squished by the max-width: 33%; rule.
    .trix-content {
      .attachment-gallery {
        > action-text-attachment,
        > .attachment {
          flex: 1 0 33%;
          padding: 0 0.5em;
          max-width: 33%;
        }
    
        &.attachment-gallery--2,
        &.attachment-gallery--4 {
          > action-text-attachment,
          > .attachment {
            flex-basis: 50%;
            max-width: 50%;
          }
        }
      }
    
      action-text-attachment {
        .attachment {
          padding: 0 !important;
          max-width: 100% !important;
        }
      }
    }
    
    .field-unit--rich-text-area-field {
      .field-unit__field {
        width: 80%;
      }
    }
    
    @import "flatpickr/dist/flatpickr.min";
    
    • gitでコミットしておく
    git add -A
    git commit -m "Administrateインストール+設定"
    

11.4.5 app/dashboards/my_post_dashboard.rb を以下に修正

  • rich_text_content を content に変更(数箇所)し、Typeを RichTextAreaField に修正
require "administrate/base_dashboard"

class MyPostDashboard < Administrate::BaseDashboard
  # ATTRIBUTE_TYPES
  # a hash that describes the type of each of the model's fields.
  #
  # Each different type represents an Administrate::Field object,
  # which determines how the attribute is displayed
  # on pages throughout the dashboard.
  #  rich_text_content: Field::HasOne,
  #  content: RichTextAreaField,
  #  content: Field::Trix,
  #  content: Field::ActiveStorage,
  ATTRIBUTE_TYPES = {
    id: Field::Number,
    title: Field::String,
    content: RichTextAreaField,
    #content:  Field::String,
    created_at: Field::DateTime,
    updated_at: Field::DateTime,
  }.freeze

  # COLLECTION_ATTRIBUTES
  # an array of attributes that will be displayed on the model's index page.
  #
  # By default, it's limited to four items to reduce clutter on index pages.
  # Feel free to add, remove, or rearrange items.
  # rich_text_content
  COLLECTION_ATTRIBUTES = %i[
  id
  title
  content
  created_at
  ].freeze

  # SHOW_PAGE_ATTRIBUTES
  # an array of attributes that will be displayed on the model's show page.
  # rich_text_content
  SHOW_PAGE_ATTRIBUTES = %i[
  id
  title
  content
  created_at
  updated_at
  ].freeze

  # FORM_ATTRIBUTES
  # an array of attributes that will be displayed
  # on the model's form (`new` and `edit`) pages.
  # rich_text_content
  FORM_ATTRIBUTES = %i[
  title
  content 
  ].freeze

  # COLLECTION_FILTERS
  # a hash that defines filters that can be used while searching via the search
  # field of the dashboard.
  #
  # For example to add an option to search for open resources by typing "open:"
  # in the search field:
  #
  #   COLLECTION_FILTERS = {
  #     open: ->(resources) { where(open: true) }
  #   }.freeze
  COLLECTION_FILTERS = {}.freeze

  # Overwrite this method to customize how my posts are displayed
  # across all pages of the admin dashboard.
  #
  # def display_resource(my_post)
  #   "MyPost ##{my_post.id}"
  # end
end
  • gitでコミットしておく
git add -A
git commit -m "MyPost用Administrate設定修正"

11.4.6 config/application.rbを修正

  • 日本語関係、タイムゾーン設定
...省略
    config.time_zone = 'Tokyo'
    config.active_record.default_timezone = :local
    config.i18n.default_locale = :ja
    config.i18n.load_path += Dir[Rails.root.join('config', 'locales', '**', '*.{rb,yml}').to_s]
  end
end

11.4.7 i18n_generatorsで日本語用ファイル生成

  • config/locales/translation_ja.yml を確認
  1. app/dashboards/my_post_dashboard.rb を以下に修正
    ... 省略
        #content: RichTextAreaField,
        content:  Field::String,
    ... 省略
    
  2. i18n_generatorsで日本語用ファイル生成
    rails db:migrate
    rails g i18n ja
    # rails g i18n_locale ja
    # rails g i18n_translation ja
    
  3. app/dashboards/my_post_dashboard.rb を以下に修正
    ... 省略
        content: RichTextAreaField,
        #content:  Field::String,
    ... 省略
    
    • gitでコミットしておく
    git add -A
    git commit -m "日本語関係設定修正"
    

11.5 railsサーバーを起動して、ブラウザで確認

rails server -b 0.0.0.0

11.6 この章のまとめ

  • 前はrails_adminを使ってみたが、今回はAdministrateというgemを利用して、Rails6でAction Textを含むクラスの管理画面を作ってみた
  • rails_adminでやった時には、画像添付ボタンが表示されてなかった(私の設定方法が悪かったのかもしれんが)が、Administrateの方は、公式サイトに記述されてる方法で、ACTION TEXTの編集で画像追加ボタンが使えた
  • 相当沢山設定変更しないと動かなかった
  • モデルをディレクトリ以下に作成する名前だとエラーになる、モデル名に::が含まれないように(まとめディレクトリ以下にモデルを作成)した方が良いようだ(ダメな例 Dialy::Post, これを改善するとすると モデル名は DialyPost)

11.7 追記

  • 以下でも動くようです
  • //= link administrate-field-trix/application.css があるために、Gemfileに gem ‘administrate-field-trix’ がないとダメだったようです。

11.7.1 app/assets/config/manifest.js が以下

  • http://localhost:3000/adminにアクセスした時に出るエラーより
  • //= link administrate-field-trix/application.css を削除
... 省略
//= link administrate/application.css
//= link administrate/application.js
  1. Gemfileが 以下
    • gem “administrate” 以下をコメントアウト
    # gem 'image_processing'
    # gem 'rails_admin'
    gem 'rails-i18n', '~> 6.0.0' # For 6.0.0 or higher
    gem 'i18n_generators'
    gem 'devise'
    
    gem "administrate" 
    # gem 'administrate-field-active_storage'
    # gem 'mini_magick'
    # gem 'administrate-field-trix'
    # gem 'trix-rails', require: 'trix'
    

12 後も文書追加していきます。

13 この文書のチェンジログ

  • 2020/02/25 初版
  • 2020/02/25 初めてのプロジェクト作成 の章追加
  • 2020/02/25 scaffoldを利用したモデルの作成 の章追加
  • 2020/02/25 scaffoldのカスタマイズ の章追加
  • 2020/03/01 Action Textを試してみる の章追加
  • 2020/03/04 Action Textを試してみる2 の章追加, Action Textを試してみる の章の動画リンク削除
  • 2020/03/05 ちゃちゃっと日記を作ってみる の章追加
  • 2020/03/05 一旦scaffoldで生成したモデルを破壊し、作り直す手順 の章追加
  • 2020/03/09 mailアドレスでログイン出来る機能をつけてみる(diverse) の章追加
  • 2020/03/09 Rails6 + Administrate + Action Text の章追加
  • 2020/03/11 Rails6 + Administrate + Action Text の最後に情報追加

著者: NM Max

Created: 2020-03-11 水 12:53

Validate

コメントを残す

メールアドレスが公開されることはありません。 が付いている欄は必須項目です