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 1 year has passed since last update.

記事にコメント機能④

Posted at

create actionを実装

投稿して、保存する。
app/controllers/comments_controller.rb
記事を取得して、コメントして、ビルドする。

  def create
    article = Article.find(params[:article_id])
    comment = article.comments.build()
    comment.save
  end

private
  def comment_params
  params.require(:comment).permit(:content)
  end

コメントの中のコンテントのしか保存しない

保存されなかった時の処理

if comment.save
  redirect_to article_path(article)
else
  flash.new[:error] = '更新できませんでした'
  render :new
end

redirect_to article_path(article):記事詳細ページに戻るという意味

これで、保存できるはずなので、一旦保存を実施してみる。
保存できているかの確認をするため、
rails コンソール

$Comment.last

先ほど投稿したものを確認できる。

app/models/comment.rb
コンテントが絶対に入ってないといけないよ!とする。

validates :content, presence: true

こうすると、記事を何も書かずに保存しようとすると、Contentを入力してくださいとなる。

これで、保存機能実装👍

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?