cloud9_note

cloud9に限らないメモ

View on GitHub

Ruby on Rails

install

gem install rails

init

# .gitファイルが作成されるので、リモートリポジトリの生成は後でやる。
rails new ${プロジェクト名}

sqliteでエラーになった場合

エラーメッセージに出ているが・・・

sudo apt-get install libsqlite3-dev

起動

rails s

任意のIPアドレスから接続する

rails s -b 0.0.0.0

参考

コントローラーの生成

rails g controller greetings index

実行結果

      create  app/controllers/greetings_controller.rb
       route  get 'greetings/index'
      invoke  erb
      create    app/views/greetings
      create    app/views/greetings/index.html.erb
      invoke  test_unit
      create    test/controllers/greetings_controller_test.rb
      invoke  helper
      create    app/helpers/greetings_helper.rb
      invoke    test_unit

コントローラー

app/controllers/greetings_controller.rb

class GreetingsController < ApplicationController
  def index
  end
end

ビューテンプレート

app/views/greetings/index.html.erb

<h1>Greetings#index</h1>
<p>Find me in app/views/greetings/index.html.erb</p>

ルーター

config/routes.rb

Rails.application.routes.draw do
  get 'greetings/index'
  # Define your application routes per the DSL in https://guides.rubyonrails.org/routing.html

  # Reveal health status on /up that returns 200 if the app boots with no exceptions, otherwise 500.
  # Can be used by load balancers and uptime monitors to verify that the app is live.
  get "up" => "rails/health#show", as: :rails_health_check

  # Defines the root path route ("/")
  # root "posts#index"
end

アプリケーションの作成(Scaffold)

コントローラだけではなく、ModelやDB定義もまとめて生成してくれる。
MVCモデルベースの機能を一通り作成する。CRUDに対応した機能等。

rails g scaffold book title:string description:text

モデル

app/models/book.rb

class Book < ApplicationRecord
end

追加されるルート

bookで生成するとURLはbooksになる。

       books GET    /books(.:format)             books#index
             POST   /books(.:format)             books#create
    new_book GET    /books/new(.:format)         books#new
   edit_book GET    /books/:id/edit(.:format)    books#edit
        book GET    /books/:id(.:format)         books#show
             PATCH  /books/:id(.:format)         books#update
             PUT    /books/:id(.:format)         books#update
             DELETE /books/:id(.:format)         books#destroy

マイグレーション

DB作成を行う。
dbディレクトリ配下のrbが実行される。

ruby db:migrate

リンクの貼り方

<%= link_to 'Show', book %>

'Show'が表示文字列、bookがURL。

erbファイルの編集例



<p style="color: green"><%= notice %></p>

<h1>Books</h1>

<table>
  <thead>
    <tr>
      <th>Title</th>
      <th>Description</th>
      <th calspan="3"></th>
    </tr>
  </thead>

  <tbody>
    <% @books.each do |book| %>
    <tr>
      <td><%= book.title %></td>
      <td><%= book.description %></td>
      <td><%= link_to 'Show', book %></td>
      <td><%= link_to 'Edit', edit_book_path(book) %></td>
      <td><%= link_to 'Destroy', book, method: :destroy, data: {confirm: 'Are you sure?'} %></td>
    </tr>
    <% end %>
  </tbody>
</table>
</div>
<p>
<%= link_to "New book", new_book_path %>
</p>


部分テンプレート

呼ぶ側


<p style="color: green"><%= notice %></p>

<h1>Books</h1>

<table>
  <thead>
    <tr>
      <th>Title</th>
      <th>Description</th>
      <th calspan="3"></th>
    </tr>
  </thead>

  <tbody>
    <!-- この1行だけで呼べる。@books.eachは配列 -->
    <%= render partial: "item", collection: @books.each , as: :book %>
  </tbody>
</table>
</div>
<p>
<%= link_to "New book", new_book_path %>
</p>

呼ばれる側

app/views/books/_item.html.erb
ファイル名に_が必要。


<tr>
  <td><%= book.title %></td>
  <td><%= book.description %></td>
  <td><%= link_to 'Show', book %></td>
  <td><%= link_to 'Edit', edit_book_path(book) %></td>
  <td><%= link_to 'Destroy', book, method: :destroy, data: {confirm: 'Are you sure?'} %></td>
</tr>

部分テンプレート 実装例(2)

new.rbindex.rbに移したときの処理。
taskmanagerrbファイルで初期化した変数名なので、rbの対象メソッドでnewする必要がある。



<!-- 新規作成 -->
<%= render "new", taskmanager: @taskmanager %>


taskmanagers_controller.rb

  def index
    @taskmanager = Taskmanager.new
  end

Active Recode

RailsのMVCモデルの「M」。
ORMの機能を持つ。
アプリケーションの作成(Scaffold)の際にも作成される。

classDiagram

    class Book

    class ApplicationRecord

    class ActiveRecord 
    class Base 
        ActiveRecord *-- Base : Contains
    
    ApplicationRecord --|> Base
    Book --|> ApplicationRecord

Modelの作成(generate model)

rails g model ${Model} ${変数名}:${型名} ...

rbファイルだけが生成される。DB定義の更新にはマイグレーションが必要。

DB定義

db.schema.rbに作成される。

マイグレーション概要

db/migrate配下のファイルを実行する。
主なコマンドはrails db:migreateだが、rails db:${その他のコマンド}で色々できる。

シード(seed)

予めDBに登録しておきたいマスタなどのデータ。
db/seeds.rbに記載する。

バリデーション

Modelに追加する。

実装例

app/models/${モデル名}.rb

class Book < ApplicationRecord
    # titleが空の場合、エラーとする。
    validates :title, presence: true
    # titleが重複している場合、エラーとする。
    validates :title, uniqueness: true
    # titleが空かつdescriptionが入力されている場合はエラーとする。
    validates :description, absence: true , unless: :title?
    # descriptionが100文字以上の場合、エラーとする。
    validates :description, length: { maximum: 100 }
end

フォームオブジェクト

バリデーションはModel(DBの登録に使用するクラス、ApplicationRecordを継承している)に記載する。
特定のモデルに限定しないか、データベースの登録と関係ないチェックはフォームオブジェクトを使用する。

実装例

# ファイルは一般的にapp/forms配下に配置
mkdir app/forms
touch app/forms/acceptance.rb

app/forms/acceptance.rb

# いずれ書く

railsコマンド

パス一覧を取得する

rails routes

Modelが持っている変数を表示する

railsコンソールを使用する。

rails console
# 名前だけほしい
Book.column_names
# 型もほしい
${Model}.columns.each do |column|
    puts "#{column.name}: #{column.type}"
end

db:migrate

rails generate migration ChangeStatusToStringInTaskmanagers
# db/migrate/配下にrbファイルが作成される。

db/migrate/yyyyMMddHHmmdd_change_status_to_string_in_taskmanagers.rb

# DBのtaskmanagers.statusの型をstringに変更する。
class ChangeStatusToStringInTaskmanagers < ActiveRecord::Migration[8.0]
  def change
    change_column :taskmanagers, :status, :string
  end
end
# 適用する
rails db:migrate

Tailwind導入

bundle add tailwindcss-rails
rails tailwindcss:install

参考

bulma CSS導入

Gemfileに下記を追記。

gem "bulma-rails"

gem "cssbundling-rails", "~> 1.4"

bundle install

# bulma cssを導入する。
# npmを使う
npm install bulma

# application.cssをapplication.scssに名前変更。
# ファイルがない場合は作成する。
cp app/assets/stylesheets/application.css app/assets/stylesheets/application.sass.scss

# application.scssにimport文を追記
echo '@import "bulma/bulma";' >> app/assets/stylesheets/application.sass.scss

# CSSをビルドする。app/assets/builds/application.cssファイルが生成される。
npm run build:css

app/views/layouts/application.html.erb
application.cssをインポートする。

<%= stylesheet_link_tag "application", "data-turbo-track": "reload" %>

注記

比較的新しいアプローチ。 もっとかんたんな方法があるらしい。app/views/layouts/application.html.erbにベタ書きするのが一番楽だったが…