【本日の学習内容:CRUDアプリの流れ(途中まで)】
CRUDアプリ作成の流れについて、根幹の部分の流れをまとめました。
--新規投稿機能の実装--
✅ルーティング
Rails.application.routes.draw do
get '/users', to:'users#index'
end
✅コントローラー
手動でusers_controllerファイルを作成。
class UsersController < ApplicationController
# 新規登録画面に対応するアクション
def new
# Userオブジェクトを作る
@user = User.new
end
end
✅モデル
rails g model user コマンドを実行することで、テーブルとそれに対応するモデルを作成。同時にマイグレーションファイルも作成される。
✅マイグレーションファイル
データベースにどのような構造のテーブルを作成するかを指定する。
class CreateUsers < ActiveRecord::Migration[6.0]
def change
create_table :users do |t|
t.string :name
t.integer :age
t.timestamps
end
end
end
✅ビュー
手動でnew.html.erbを作成。
<%= form_with model:@user, url: "/users", method: :post, local: true do |f| %>
<p>投稿</p>
<p>お名前:<%= f.text_field :name %></p>
<p>年齢:<%= f.text_field :age%></p>
<input type="submit" value="送信">
<% end %>