LoginSignup
0
0

More than 3 years have passed since last update.

コメント投稿機能

Posted at

アウトプット備忘録です。

簡単な掲示板のコメント機能を実装していたのですが、エラーはでないのですが投稿出来ず。
下記コード

top_page>show.html.haml
.main
  = form_for @comment , url:{controller: 'responses', action: 'create'}do |f|
    .main__consultation
      .main__consultation__title
        お悩み一覧
      .main__consultation__text
        = @toppage.contents
    .main__comment
      = f.text_area :comment, class: "main__comment__form"
      .main__comment__sent
        = f.submit "投稿する"
      .main__comment__text
        <コメント一覧>
      -if @comments
        -@comments.each do |response|
          .main__comment__main
            .main__comment__main__name
              = response.user.name
            .main__comment__main__form
              = response.comment
response_controller.rb
class ResponsesController < ApplicationController
  def create
    response = Response.create(response_params)
    redirect_to root_path
  end

  private
  def response_params
    params.require(:response).permit(:comment).merge(user_id: current_user.id, top_page_id: params[:top_page_id])
  end
end
top_page_controller.rb
class TopPageController < ApplicationController
  def index
    @toppages = TopPage.all
  end

  def new
    @toppage = TopPage.new
  end

  def create
    TopPage.create(top_page_params)
    redirect_to top_page_index_path
  end

  def show
    @toppage = TopPage.find(params[:id])
    @comment = Response.new
    @comments = @toppage.responses.includes(:user)
  end

  private
  def top_page_params
    params.require(:top_page).permit(:contents,:name).merge(user_id: current_user.id)
  end
end

これでエラーはでないのですが投稿はされず。
binding.pryをかけた結果
20200807101155.png

top_page_id(投稿ページのid)に何も入っていないことが原因?と考えられたので

下記修正

top_page>show.html.haml
.main
  = form_for @comment , url:{controller: 'responses', action: 'create'}do |f|
    .main__consultation
      .main__consultation__title
        お悩み一覧
      .main__consultation__text
        = @toppage.contents
    .main__comment
      = f.text_area :comment, class: "main__comment__form"
      = hidden_field_tag :top_page_id, value: @toppage.id
      .main__comment__sent
        = f.submit "投稿する"
      .main__comment__text
        <コメント一覧>
      -if @comments
        -@comments.each do |response|
          .main__comment__main
            .main__comment__main__name
              = response.user.name
            .main__comment__main__form
              = response.comment

= hidden_field_tag :top_page_id, value: @toppage.id
を追加しました。

今回はfield_tagは1つの単体のパラメーターを渡すときだけ使用可能の様。
はじめて初めて使いました。
こちらも参考にしたいところ
https://qiita.com/yukiweaver/items/8e1e01fd6dcadf36d420

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