質問をすることでしか得られない、回答やアドバイスがある。

15分調べてもわからないことは、質問しよう!

新規登録して質問してみよう
ただいま回答率
85.47%
Ruby

Rubyはプログラミング言語のひとつで、オープンソース、オブジェクト指向のプログラミング開発に対応しています。

Ruby on Rails

Ruby on Railsは、オープンソースのWebアプリケーションフレームワークです。「同じことを繰り返さない」というRailsの基本理念のもと、他のフレームワークより少ないコードで簡単に開発できるよう設計されています。

Q&A

解決済

1回答

314閲覧

railsでコメント機能を実装したい

NakaShun_1129

総合スコア20

Ruby

Rubyはプログラミング言語のひとつで、オープンソース、オブジェクト指向のプログラミング開発に対応しています。

Ruby on Rails

Ruby on Railsは、オープンソースのWebアプリケーションフレームワークです。「同じことを繰り返さない」というRailsの基本理念のもと、他のフレームワークより少ないコードで簡単に開発できるよう設計されています。

0グッド

0クリップ

投稿2020/05/11 12:28

現在、投稿に対してのコメント機能を実装しています。
しかし、下記のエラーが出てしまいます。
記述ミスを探したのですが特に見つかりません。
どなたか分かる人はいますでしょうか。

イメージ説明

route.rb resources :recruitments do resources :comments, only: :create resource :favorites, only: [:create, :destroy] end

モデル

comment.rb class Comment < ApplicationRecord belongs_to :recruitment belongs_to :user end
user.rb class User < ApplicationRecord devise :database_authenticatable, :registerable, :recoverable, :rememberable, :validatable, :omniauthable has_many :recruitments has_many :favorites has_many :favorited_recruitments, :through => :favorites, :source => :recruitment has_many :comments end
recruitment class Recruitment < ApplicationRecord belongs_to :user has_many :favorites has_many :favorited_users, :through => :favorites, :source => :user has_many :comments end

コントローラー

CommentsController class CommentsController < ApplicationController def create Comment.create(comment_params) redirect_to "/recruitments/#{comment.recruitment.id}" # コメントと結びつく募集の詳細画面に遷移する end private def comment_params params.require(:comment).permit(:text).merge(user_id: current_user.id, recruitment_id: params[:recruitment_id]) end end
RecruitmentsController class RecruitmentsController < ApplicationController def show @recruitment = Recruitment.find(params[:id]) @user = @recruitment.user @favorite = Favorite.new @comments = @recruitment.comments.includes(:user) end end

ビュー

recruitments/show.html.haml .container - if current_user = form_with(model: [@recruitment, @comment], local: true) do |form| = form.text_area :text, placeholder: "コメントする", rows: "2" = form.submit "SEND" - else %strong %p ※※※ コメントの投稿には新規登録/ログインが必要です ※※※ .comments %h4 <コメント一覧> - if @comments - @comments.each do |comment| %p %strong = link_to comment.user.nickname, "/users/#{comment.user_id}" : = comment.text

気になる質問をクリップする

クリップした質問は、後からいつでもMYページで確認できます。

またクリップした質問に回答があった際、通知やメールを受け取ることができます。

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

guest

回答1

0

自己解決

RecruitmentsControllerに以下の記述がありませんでした。

@comment = Comment.new

form_withを使用して、comments#createにアクション先を飛ばしたいので、
@comment = Comment.newとインスタンス生成をしないといけませんでした。

投稿2020/05/11 12:36

NakaShun_1129

総合スコア20

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

あなたの回答

tips

太字

斜体

打ち消し線

見出し

引用テキストの挿入

コードの挿入

リンクの挿入

リストの挿入

番号リストの挿入

表の挿入

水平線の挿入

プレビュー

15分調べてもわからないことは
teratailで質問しよう!

ただいまの回答率
85.47%

質問をまとめることで
思考を整理して素早く解決

テンプレート機能で
簡単に質問をまとめる

質問する

関連した質問