0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

学習6日目

Last updated at Posted at 2025-06-09

今日やったこと

オリジナルアプリの1つのモデルについて、下記機能の実装
①一覧表示
②詳細表示
③新規作成・保存
④編集・更新

内容

①一覧表示

モデルとコントローラを作成。

rails g model hoge
rails g controller hoges

基本的なCRUD処理が必要になるので、ルーティングを記述。
(routes.rbの記述例)

resources :hoges

その後、下記コマンドを実行し、それぞれのアクションに対応するパス名を確認。

$ rails routes

モデルと同時に作成されるマイグレーションファイルに必要なカラム情報を追記し、マイグレート実行。

rails db:migrate

必要に応じて、モデルにバリデーションを記述。
(hoge.rbの記述例)

validates :column_name, presence: true

コントローラに下記を記述。
併せて、views/hoges/index.html.erbも作成。
(hoges_controller.rbの記述例)

def index
    @hoges = Hoge.all
end

ビューでは一旦全データについて特定のカラム情報を一覧表示させたいので、下記を記述。
ついでに詳細画面へのリンクも付けておく。
(views/hoges/index.html.erbの記述例)

<% @hoges.each do |hoge| %>
    <%= link_to "#{hoge.column_name}", hoge_path(hoge) %>
<% end %>

②詳細表示

コントローラに下記を記述。
併せて、views/hoges/show.html.erbを作成。
(hoges_controller.rbの記述例)

def show
    @hoge = Hoge.find(params[:id])
end

ビューでは一旦全カラムの情報を表示させたいので、下記を記述。
ついでに編集画面へのリンクも出しておく。
(views/hoges/show.html.erbの記述例)

<%= @hoge.column_name1 %>
<%= @hoge.column_name2 %>
<%= @hoge.column_name3 %>
<%= link_to "edit hoge", edit_hoge_path(@hoge) %>

③新規作成・保存

コントローラにnewとcreateアクションを定義。
ストロングパラメータも記述。
保存できなかった場合の処理は一旦無視して、正常に保存できる処理のみ記述。保存後はルートパスに遷移させるようにする。

(hoges_controller.rbの記述例)

def new
  @hoge = Hoge.new
end

def create
  Hoge.create(hoge_params)
  redirect_to root_path
end

private
def hoge_params
  params.require(:hoge).permit(:column_name1,:column_name2,...)
end

併せて、views/hoges/new.html.erbを作成し、下記を記述。
(views/hoges/new.html.erbの記述例)

<%= form_with model: @home do |form| %>
  <%= f.text_field :column_name1 %>
  <%= f.text_field :column_name2 %>
  <%= f.text_field :column_name3 %>
  <%= f.submit "submit" %>
<% end %>

④編集・更新

コントローラにedit・updateアクションを定義し、下記を記述。
基本的にはnew・createと同じ流れだが、空のインスタンスではない点と、メソッドがcreateではなくupdateとなる。
views/hoges/edit.html.erbの記述はnew.html.erbと同じ。
(hoges_controller.rbの記述例)

def edit
  @hoge = Hoge.find(params[:id])
end

def update
  Hoge.update(hoge_params)
  redirect_to root_path
end

感想

Railsの命名規則を守らないと予想外のエラーに遭遇するので、注意したい。
内容をそのままQiita記事に書いていくと時間がかかるので、要点のみ記述するようにしたい。

0
0
1

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?