MVC構造とルーティング
Ruby on Rails
ディレクトリ構成・routes・RESTful
ディレクトリ構成
Rails アプリの主要ファイルと役割
rails new myapp --database=postgresql
rails new myapp --api # APIモード
rails new myapp -T # テストなし
rails new myapp --javascript=importmap # デフォルト
# ディレクトリ構成
app/
├── controllers/ # リクエスト処理
│ └── application_controller.rb
├── models/ # ビジネスロジック・DB操作
├── views/ # HTML テンプレート
├── helpers/ # ビューヘルパー
├── jobs/ # バックグラウンドジョブ
├── mailers/ # メール送信
├── channels/ # ActionCable (WebSocket)
└── assets/ # CSS・JS・画像
config/
├── routes.rb # URLルーティング
├── database.yml # DB接続設定
├── application.rb # アプリ設定
└── environments/ # 環境別設定
db/
├── migrate/ # マイグレーションファイル
└── schema.rb # 現在のスキーマ
spec/ (or test/) # テストコード
Gemfile # 依存関係
# よく使う rails コマンド
rails server # サーバー起動(rails s)
rails console # IRBコンソール(rails c)
rails generate model User name:string age:integer
rails generate controller Users index show
rails generate scaffold Post title:string body:text
rails db:migrate
rails db:rollback
rails routes # ルート一覧
rails routes | grep user # 絞り込みルーティング
RESTful routes・名前付きルート・ネスト・制約
Rails.application.routes.draw do
# RESTful リソース(7アクションを自動定義)
# index, show, new, create, edit, update, destroy
resources :posts
# 一部のアクションのみ
resources :users, only: [:index, :show, :create]
resources :sessions, except: [:edit, :update]
# シングルリソース(IDなし)
resource :profile # show, new, create, edit, update, destroy
# ネストしたリソース
resources :posts do
resources :comments, only: [:index, :create, :destroy]
member do
post :publish # /posts/:id/publish
post :unpublish
end
collection do
get :drafts # /posts/drafts
get :featured
end
end
# 名前空間
namespace :admin do
resources :users
resources :posts
end
# => /admin/users, Admin::UsersController
scope '/api/v1', module: 'api/v1', as: 'api_v1' do
resources :users
end
# カスタムルート
get '/about', to: 'pages#about', as: :about
post '/login', to: 'sessions#create'
delete '/logout', to: 'sessions#destroy'
get '/search', to: 'search#index'
# ルートへのリダイレクト
get '/old-path', to: redirect('/new-path')
get '/blog/:id', to: redirect('/posts/%{id}')
# デフォルトルート
root 'home#index'
# 制約
constraints(id: /\d+/) do
resources :products
end
end名前付きルートヘルパー
# resources :posts が生成するヘルパー
posts_path # /posts (GET index)
post_path(@post) # /posts/1 (GET show)
new_post_path # /posts/new (GET new)
edit_post_path(@post) # /posts/1/edit (GET edit)
# _url vs _path
posts_path # '/posts' (相対パス)
posts_url # 'http://example.com/posts' (絶対URL)
# パラメーター付き
posts_path(page: 2, per: 10)
# => '/posts?page=2&per=10'
post_path(@post, format: :json)
# => '/posts/1.json'
# ネストしたルート
post_comments_path(@post)
# => '/posts/1/comments'
# namespace
admin_users_path
# => '/admin/users'