0
0

Railsを使ってアプリを作る(基礎中の基礎)

Posted at

はじめに

今回は、railsをつかってアプリをつくり、デプロイまでの基本的な流れをまとめました。
基礎中の基礎という通り、画面にHello,worldを表示するだけのアプリになります。
エディタはVSCodeを用いて、バージョン管理をGitで行い、Renderへデプロイします。
使用ハードはmacbook m2です。
Rubyはデフォルトで入ってるので、Railsのインストールから始めます。

Railsをインストール

$ gem install rails

-vを行うことでバージョンの指定もできます。

$ gem install rails -v 7.0.4.3

次にbundlerをインストールします。

$ gem install bundler

アプリを作る

Railsプロジェクト用のenvironmentディレクトリを作ります。

$ cd         
$ mkdir environment
$ cd environment/

rails newを実行する。
このとき、PCにインストールされているバージョンを指定することで、同じバージョンのrailsで作成できます。

$ rails _7.0.4.3_ new hello_app

Bundler

railsアプリを新規作成したあとは、bundlerを実行し、アプリに必要なGemをインストールします。

gemfileに使用するgemを追加したり、バージョン指定するなど変更を行ったあとは、bundle installを忘れずに。

$ bundle install
$ bundle lock --add-platform x86_64-linux

2行目は、追加されることで、bundle installする際に、Linux用(x86_64-linux)のnokogiri gemが入るようになる。これをしないとデプロイした際、エラーになることがあるみたい・・・。

rails serverを立ち上げる

$ rails server

上記コマンドを実行することでローカルサーバーが立ち上がる。
Chromeでlocalhost:3000を検索。

Hello,worldを表示してみよう

app/controllers/application_controller.rbに以下を追記。

class ApplicationController < ActionController::Base

  def hello
    render html: "hello, world!"
  end
end

routesのrootを更新。

Rails.application.routes.draw do
  root "application#hello"
end

これで画面にhello,worldの文字が出てくる。

Githubでソースコードを管理

いろいろな変更を行った際は、こまめにgithubにpushしよう。
まずはgithub公式にいき、レポジトリを新たに作成。

作成後、エディタへ戻り、

$ git init
$ git add -A
$ git commit -m "first commit"

上記のコマンドで、ローカルレポジトリを作成するのと、いわゆるセーブをします。

あとはいまの開発環境と、Githubで先程作成したレポジトリを連携させます。

$ git remote add origin https://github.com/ユーザーID/アプリケーション名.git

これで連携完了。
あとはリモートでcommitした内容をgithubにpushする。

$ git push origin main

デプロイする

ここまで来たら、本番環境にデプロイする作業。
今回はRenderを使用してデプロイします。

まずはmaster.keyとcredentialを作成する。

# master.keyがすでにあるかどうか確認する
$ ls config/master.key

# 既存のcredentialsを削除する
$ rm config/credentials.yml.enc

# 新しいcredentialsとmaster.keyを作成
$ rails credentials:edit

新たに出来上がったmaster.keyの中身をコピーします。

Renderに移動し、新たにWeb serviceを作成し、githubで作ったアプリと同期します。
最後に環境変数のRAILS_MASTER_KEYに先ほどコピーしたものを貼り付け、create web serviceします。

エラーが出なければ完成!

0
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
0
0