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?

More than 3 years have passed since last update.

Rails コメント機能 コード解説(ビューの作成)

0
Posted at

ビューの作成

posts/show.html.erb
<%= form_with(model: [@post, @comment], local: true) do |f| %>
<textarea name="content"><%= @comment.content %></textarea>
<input type="submit" value="コメントする">
<% end %>
<p>コメント件数<%= @comments.count %></p>
<% @comments.each do |c| <div>
<a href="/users/<%= c.user.id %>"><%= c.user.name %></a>
<%= c.content %>
<%= link_to("削除", "/comments/#{c.user.id}/destroy", {method: "post"}) %>
<% end %>
<%= paginate @comments %>

コードの解説

1行目・・postコントローラーにcommentコントローラーのルーティングがネストしている。
[(親)@インスタンス変数, (子)@インスタンス変数]の順で記述するようにする。
local: trueと引数を渡す事で、これが通常のHTTPリクエストになり、ページ全体が返ってくる
2行目・・コメントの内容の表示
3行目・・タグのtype属性の値にsubmitを指定すると、フォームの送信ボタンを作成します。
5行目・・コメント数の習得
6行目・・要素を1つずつ取得してcに代入
7行目・・c.user.id=comment.user.id,c.user.name=comment.user.nameと同義
8行目・・c.content=comment.contentと同義
11行目・・viewでページネーションを表示させたい

引用記事

ネストした form_withの理解を深める
[Rails] form_with の2種類の書き方
form_withのlocal: trueって必要なん?これ何なん?(Ruby on Rails)
HTML5タグリファレンス
【初心者向け】コメント機能作成追加
【Rails】 世界で一番分りやすく詳しいcountメソッドの使い方
【Rails初心者】ページネーションを実装して自分好みにデザインを変える

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?