Railsにこれから初めて触れる人を対象にしたチュートリアルです
ActiveAdminを使用した求人募集サイトを作成するチュートリアルです!
まず、rails newを実行し、Railsアプリのひな型を作成します
rails new hellojob
次に、作成したRailsアプリのディレクトリへと移動します
cd hellojob
先ほどのrails newでsqlite3のインストールがエラーになっている場合は、以下のようにバージョンを修正します
gem 'sqlite3', '1.3.13'
その後、bundle installを実行します
bundle install
これでOKです!
まず、Gemfileに以下のgemを追加します
# Using ActiveAdmin
gem 'devise'
gem 'activeadmin'
その後、bundle installを実行します
bundle install
そして、rails g active_admin:installを実行します
rails g active_admin:install
その後、rails db:migrateを実行します
rails db:migrate
rails db:seedを実行し、ログイン用ユーザーのデータを作成します
rails db:seed
あとはrails sを実行し、localhost:3000/adminにアクセスします
localhost:3000/adminにアクセスするとログインフォームが表示されます
IDとパスワードは以下の通りです
ID:admin@example.com
PASS:password
ログインできればActiveAdminの導入は完了です!
求人データを取り扱うJobモデルを作成します
rails g model Job title:string content:text
その後、rails db:migrateを実行します
rails dbmigrate
あとは、rails generate active_admin:resource jobを実行してActiveAdminで管理できるようにします
rails generate active_admin:resource job
これでActiveAdminの管理画面から求人データを作成できるようになります
まず、config/application.rbにconfig.i18n.default_locale = :jaを追加します
config.i18n.default_locale = :ja
その後、config/locales/ja.ymlを追加します
ja:
  time:
    formats:
      long: "%d/%m/%Y %H:%M"
これでActiveAdminの管理画面が日本語化されました!
activeadmin_medium_editorを使い、求人データにリッチテキストエディターを導入します
まず、Gemfileにgemを追加します
gem 'activeadmin_medium_editor'
その後、bundle installを実行し、gemをインストールします
bundle install
次に、app/assets/stylesheets/active_admin.scssにscssを追加します
@import 'activeadmin/medium_editor_input';
@import 'activeadmin/medium_editor/themes/default.css';
そして、app/assets/javascripts/active_admin.js.coffeeをapp/assets/javascripts/active_admin.jsへとリネームし、
//= require active_admin/base
//= require activeadmin/medium_editor/medium_editor
//= require activeadmin/medium_editor_input 
実際にActiveAdmin画面でエディターを使用できるようにしてみましょう!
app/admin/jobs.rbを以下のように編集します
ActiveAdmin.register Job do
    permit_params :title, :content
    form do |f|
        f.inputs 'Job' do
            f.input :title
            f.input :content, as:  :medium_editor, input_html: { data: { options: '{"spellcheck":false,"toolbar":{"buttons":["bold","italic","underline","anchor"]}}' } }
        end
        f.actions
    end
end
ActiveAdminではform doのようにコードを追記することで各Viewをカスタマイズすることができます
今回は、rails g scaffoldで作成している_form.html.erbをカスタマイズしているイメージですね
さらに、エディターで作成した求人内容を正しく表示させるために、showページもカスタマイズしていきます
先ほどと同様にapp/admin/jobs.rbに以下のコードを追加します
    show do
        attributes_table do
            row :title
            row (:content) { |job| sanitize(job.content) }
        end
        active_admin_comments
    end
さらに、求人データを管理するindexページでは求人のタイトルだけを表示できるようにします
app/admin/jobs.rbに以下のコードを追加し、indexをカスタマイズします
    index do
        column :id
        column :title
         actions defaults: true do |job|
        end
    end
これでactiveadmin_medium_editorは導入できました!
rails g controllerコマンドを使い、求人の一覧ページ&詳細ページを作成します
rails g controller jobs index show
その後、app/controllers/jobs_controller.rbを以下のように作成します
class JobsController < ApplicationController
 before_action :set_job, :only => [:show]
  def index
    @jobs = Job.all
  end
  def show
  end
  private
    def set_job
      @job = Job.find(params[:id])
    end
end
app/views/jobs/index.html.erbを以下のように作成します
<% @jobs.each do |job| %>
    <%= link_to "#{job.title}", job_path(job) %>
<% end %>
app/views/jobs/show.html.erbを以下のように作成します
<h1>Title</h1>
<p>
    <%= @job.title %>
</p>
<h1>Content</h1>
<p>
    <%= sanitize @job.content %>
</p>
最後に、config/routes.rbを以下のように変更します
Rails.application.routes.draw do
 root 'jobs#index'
  resources :jobs, :only => [:index, :show]
  devise_for :admin_users, ActiveAdmin::Devise.config
  ActiveAdmin.routes(self)
  # For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html
end
これで求人の一覧ページ&詳細ページを実装できました!
このままではデザインなどが簡素すぎるのでBootstrapを使いたいと思います。
まず、Gemfileにgem 'bootstrap', '~> 4.2.1'とgem 'jquery-rails'を追加し、bundle installします。
gem 'bootstrap', '~> 4.2.1'
gem 'jquery-rails'
bundle install
もし、gemの依存関係でうまくいかない場合は、bundle updateを実行してからbundle installを実行してください
bundle update
bundle install
その後、app/assets/javascripts/application.jsとapp/assets/stylesheets/application.scssを下記のように変更します
// This is a manifest file that'll be compiled into application.js, which will include all the files
// listed below.
//
// Any JavaScript/Coffee file within this directory, lib/assets/javascripts, or any plugin's
// vendor/assets/javascripts directory can be referenced here using a relative path.
//
// It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the
// compiled file. JavaScript code in this file should be added after the last require_* statement.
//
// Read Sprockets README (https://github.com/rails/sprockets#sprockets-directives) for details
// about supported directives.
//
//= require rails-ujs
//= require activestorage
//= require trix
//= require jquery3
//= require popper
//= require bootstrap-sprockets
//= require turbolinks
//= require_tree .
/*
 * This is a manifest file that'll be compiled into application.css, which will include all the files
 * listed below.
 *
 * Any CSS and SCSS file within this directory, lib/assets/stylesheets, or any plugin's
 * vendor/assets/stylesheets directory can be referenced here using a relative path.
 *
 * You're free to add application-wide styles to this file and they'll appear at the bottom of the
 * compiled file so the styles you add here take precedence over styles defined in any other CSS/SCSS
 * files in this directory. Styles in this file should be added after the last require_* statement.
 * It is generally better to create a new file per style scope.
 *
 *= require_tree .
 *= require_self
 */
 @import "trix";
 @import "bootstrap";
その後、config/boot.rbを以下のように修正します
ENV['BUNDLE_GEMFILE'] ||= File.expand_path('../Gemfile', __dir__)
ENV['EXECJS_RUNTIME'] = 'Node'
require 'bundler/setup' # Set up gems listed in the Gemfile.
require 'bootsnap/setup' # Speed up boot time by caching expensive operations.
これでBootstrapが使用できるようになりました。
最後に、app/views/layouts/_header.html.erbを作成し、app/views/layouts/application.html.erbでパーシャルとして呼び出します。
<nav class="navbar navbar-expand-lg navbar-light bg-light">
  <%= link_to "Hellojob!", root_path, class: "navbar-brand" %>
  <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarNav" aria-controls="navbarNav" aria-expanded="false" aria-label="Toggle navigation">
    <span class="navbar-toggler-icon"></span>
  </button>
</nav>
<!DOCTYPE html>
<html>
  <head>
    <title>Hellojob</title>
    <%= csrf_meta_tags %>
    <%= csp_meta_tag %>
    <%= stylesheet_link_tag    'application', media: 'all', 'data-turbolinks-track': 'reload' %>
    <%= javascript_include_tag 'application', 'data-turbolinks-track': 'reload' %>
  </head>
  <body>
    <%= render 'layouts/header'%>
    <div class="container">
      <%= yield %>
    </div>
  </body>
</html>
rails sでサーバを起動し、ナビゲーションバーが表示されていればOKです。
今の状態だと求人一覧が縦に並んでいる状態になり、かつ求人のタイトルしか記載されていません
そこで、先ほど導入したBootstrap4のCardとGirdを使いレイアウトを調整します
app/views/jobs/index.html.erbを以下のように修正します
<div class="row">
    <% @jobs.each do |job| %>
        <div class="card col-4" style="width: 18rem;">
            <div class="card-body">
                <h5 class="card-title"><%= job.title %></h5>
                <p class="card-text"><%= sanitize job.content %></p>
                <%= link_to "詳細", job_path(job), class: "btn btn-primary" %>
            </div>
        </div>
    <% end %>
</div>
これで、求人を三件ずつ横並びにしつつカード風に求人を表示させることができます!
kaminariを使い、ページネーションを実装します
まず、Gemfileにgemを追加します
gem 'kaminari'
その後、bundle installを実行します
bundle install
次に、app/controllers/jobs_controller.rbのindexアクションを以下のようにします
  PAGE_PER = 12
  def index
    @jobs = Job.all.page(params[:page]).per(PAGE_PER)
  end
後は、app/views/jobs/index.html.erbに以下のコードを追加します
<%= paginate @jobs %>
これでkaminariでのページネーションは実装完了です!
以上で、求人サイトのチュートリアルは修了です!