LoginSignup
0
0

More than 3 years have passed since last update.

Railsアプリで一覧と詳細表示機能を実装する

Posted at

一覧表示機能を実装する

投稿された全ての投稿を確認するための一覧表示機能を作成します。
indexアクションで、投稿データをDBから取得し、indexのビューで出力します。

一覧表示アクションで投稿データを取得する。

PostsControllerのindexアクションを以下のように書き換えます。
indexアクションでは、全投稿のデータをPost.allで取得し、ビューに出力するためのインスタンス変数に格納します。

app/controllers/posts_controller.rb
  def index
    @posts =Post.all
  end

一覧画面ですべての投稿を表示する

次にビューを実装します。@posts内の各Postオブジェクトの内容をテーブル形式で表示します。

app/views/posts/index.html.slim
h1 タスク一覧

= link_to '新規投稿', new_post_path, class: 'btn btn-primary'

.mb-3
table.table.table-hover
  thead.thead-default
    tr
      th= Post.human_attribute_name(:content)
      th= Post.human_attribute_name(:created_at)
  tbody
    - @posts.each do |post|
      tr
        td= post.content
        td= post.created_at

A33A1370-0D8F-4E59-8D6C-085A9FE4A43F.png

詳細表示機能を実装する

一覧画面内の投稿をクリックして、詳細画面に遷移する機能を作ります。
app/views/posts/index.html.slimの、投稿を表示している部分を以下に変えます。

app/views/posts/index.html.slim
        td= link_to post.content, post

投稿部分がリンクになり、"post/[投稿ID]"という詳細表示のURLに遷移します。URLは、Railsが推測して作ってくれます。

続いてアクションを実装します。

app/controllers/posts_controller.rb
  def show
    @post = Post.find(params[:id])
  end

findメソッドを使って詳細表示にするためのPostオブジェクトを取得しています。
params[:id]には、paramsから得られるid、リクエストされたURL"posts/[投稿id]"の[投稿id]が格納されています。

続いてビューを修正し、投稿(@post)の各属性を表示するようにします。

app/views/posts/show.html.slim
h1 投稿の詳細

.nav.justify-content-end
  = link_to '一覧'posts_path, class: 'nav-link'
table.table.table-hover
  tbody
    tr
      th= Post.human_attribute_name(:id)
      td= @post.id
    tr
      th= Post.human_attribute_name(:content)
      td= simple_format(h(@post.content), {}, sanitize: false, wrapper_tag: "div")
    tr
      th= Post.human_attribute_name(:created_at)
      td= @post.created_at
    tr
      th= Post.human_attribute_name(:updated_at)
      td= @post.updated_at

投稿内容は複数行にわたるテキストなので、改行コードを含む場合があります。改行コードはHTML自体の改行として扱われて、画面上では改行しているように見えません。文字列内の改行を<br>タグなどに変換する必要があります。
今回のsimple_formatメソッドでは、デフォルトのsanitizeオプションをfalseにし、hというメソッドでXSS(クロスサイトスクリプティング)対策を施しています。また、デザイン上の制約でwrapper_tagで<div>を指定しています。

これで、詳細表示機能が完成しました。
一覧画面で投稿をクリックすると…
7693978D-8408-42E4-BFF8-00678791F2BB.png

投稿の詳細が確認できました!

参考

現場で使える Ruby on Rails 5速習実践ガイド

0
0
0

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