Railsにこれから初めて触れる方を対象としてチュートリアルです
今回は、meta-tagsを使用したSEO対策チュートリアルになります
まず、rails newを実行し、Railsアプリのひな型を作成します
rails new meta-tags
次に、作成したmeta-tagsディレクトリへと移動します
cd meta-tags
先ほどのrails newでsqlite3のインストールがエラーになっている場合は、以下のようにバージョンを修正します
gem 'sqlite3', '1.3.13'
その後、bundle installを実行します
bundle install
それではmeta-tagsの導入を行いたいと思います
まずは、Gemfileにmeta-tagsを追加します
# Using Meta-tags
gem 'meta-tags'
その後、bundle installを行います
bundle install
bundle install後、rails generate meta_tags:installを実行します
rails generate meta_tags:install
最後にapp/views/layouts/application.html.erbに<%= display_meta_tags site: 'My First Rails' %>を追加します
<!DOCTYPE html>
<html>
  <head>
    <title>MetaTags</title>
    <%= csrf_meta_tags %>
    <%= csp_meta_tag %>
    <%= display_meta_tags site: 'My First Rails' %>
    <%= stylesheet_link_tag    'application', media: 'all', 'data-turbolinks-track': 'reload' %>
    <%= javascript_include_tag 'application', 'data-turbolinks-track': 'reload' %>
  </head>
  <body>
    <%= yield %>
  </body>
</html>
これでmeta-tagsを使ってのSEO対策が実装できました!
場合によっては、各ページごとにdescriptionを追加したい場合があると思います
その場合は、まず以下のようにapp/controllers/application_controller.rbを編集します
class ApplicationController < ActionController::Base
    before_action :set_meta_tags
    private
        def set_meta_tags
            @page_title       = 'My First Rails'
            @page_description = 'Rails tutorial for programming beginner'
            @page_keywords    = 'Rails progiramming beginner'
        end
end
次に、動きを確認するためのページを作成します
rails g controller web inde about contact
その後、app/controllers/web_controller.rbを編集します
class WebController < ApplicationController
  def index
    @page_title       = 'Index'
    @page_description = 'Rails tutorial for programming beginner Index'
    @page_keywords    = 'Rails progiramming beginner'
  end
  def about
    @page_title       = 'About'
    @page_description = 'Rails tutorial for programming beginner About'
    @page_keywords    = 'Rails progiramming beginner'
  end
  def contact
    @page_title       = 'Contact'
    @page_description = 'Rails tutorial for programming beginner Contact'
    @page_keywords    = 'Rails progiramming beginner'
  end
end
これでlocalhost:3000/web/index、localhost:3000/web/about、localhost:3000/web/contactにアクセスすると各ページの<meta>タグ内に追記されたdescriptionなどが表示されています!