Tortoise-like pace

toshibohjp

[RoRGuides] #07 個々の Post を表示する

| Comments

前回 は、Post を新規作成する仕組みについて見て来ました。今回は、他の Post の操作について見て行きたいと思います。

6.3 個々の Post を表示する

index ページにある任意の Post の show リンクをクリックした場合は、http://localhost:3000/posts/1 のような URL に遷移します。Rails はそのリソースのための show アクションへの呼び出しとして解釈し、 :id パラメータとして 1 を渡します。show アクションについては、以下のとおりです。

app/controllers/posts_controller.rb
1
2
3
4
5
6
7
8
9
10
  # GET /posts/1
  # GET /posts/1.json
  def show
    @post = Post.find(params[:id])

    respond_to do |format|
      format.html # show.html.erb
      format.json { render json: @post }
    end
  end

show アクションは、id の値でデータベース内にある単一のレコードを検索するために Post.fild を使用します。レコードを検索した後、Rails は app/views/posts/show.html.erb を使用して、検索結果を表示します。

app/views/posts/show.html.erb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
<p id="notice"><%= notice %></p>

<p>
  <b>Name:</b>
  <%= @post.name %>
</p>

<p>
  <b>Title:</b>
  <%= @post.title %>
</p>

<p>
  <b>Content:</b>
  <%= @post.content %>
</p>


<%= link_to 'Edit', edit_post_path(@post) %> |
<%= link_to 'Back', posts_path %>

6.2 Posts を編集する

Post を新規作成したように、Post を編集するのも二段階のプロセスを踏みます。最初のステップは特定の Post に伴う edit_post_path(@post) へのリクエストです。これは、Controller ないの edit アクションを呼び出します。

app/controllers/posts_controller.rb
1
2
3
4
  # GET /posts/1/edit
  def edit
    @post = Post.find(params[:id])
  end

繰り返しになりますが、new アクションと同様に edit アクションは form Partial を使用しています。しかしながら、今回はフォームは PostController への PUT アクションを行い、送信ボタンは “Update Post” と表示するでしょう。

この View によって作成されたフォームを送信すると、Controller内の update アクションを呼び出すでしょう。

app/controllers/posts_controller.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
  # PUT /posts/1
  # PUT /posts/1.json
  def update
    @post = Post.find(params[:id])

    respond_to do |format|
      if @post.update_attributes(params[:post])
        format.html { redirect_to @post, notice: 'Post was successfully updated.' }
        format.json { head :no_content }
      else
        format.html { render action: "edit" }
        format.json { render json: @post.errors, status: :unprocessable_entity }
      end
    end
  end

update アクションの中では、Rails はまず、編集中のデータベースのレコードを見つけるために、:id パラメータを edit View から受け取ります。update_attributes の呼び出しでは、リクエストから Post のパラメータ(ハッシュ)を取得し、このレコードに適用します。すべてがうまくいった場合は、ユーザーは Post の show アクションへリダイレクトされます。なにか問題が会った場合には、問題を修正するために edit アクションに戻るようにリダイレクトされます。

6.3 Post を削除する

最後に、任意の Post の destroy リンクをクリックすると、id に関連する destroy アクションが呼び出されます。

app/controllers/posts_controller.rb
1
2
3
4
5
6
7
8
9
10
11
  # DELETE /posts/1
  # DELETE /posts/1.json
  def destroy
    @post = Post.find(params[:id])
    @post.destroy

    respond_to do |format|
      format.html { redirect_to posts_url }
      format.json { head :no_content }
    end
  end

Active Record の Model インスタンスにある destroy メソッドはデータベースから対応するレコードを削除します。削除を行った後、表示するレコードが無いので、Rails はユーザーのブラウザーを Controller の index アクションにリダイレクトします。

次回へ続きます。

Comments