前提・実現したいこと
Railsで投稿アプリを作っていて、
その投稿に付いているコメントを
トップページに表示させようと思っています。
発生している問題・エラーメッセージ
undefined method `comments' for nil:NilClass
該当のソースコード
commentrb
1 2class Comment < ApplicationRecord 3 mount_uploader :image, ImageUploader 4 belongs_to :post 5 belongs_to :user 6end 7
postrb
1 2class Post < ApplicationRecord 3 mount_uploader :image, ImageUploader 4 has_many :comments 5end 6
userrb
1 2class User < ApplicationRecord 3 # Include default devise modules. Others available are: 4 # :confirmable, :lockable, :timeoutable, :trackable and :omniauthable 5 devise :database_authenticatable, :registerable, 6 :recoverable, :rememberable, :validatable 7 has_many :comments 8end 9
commentcontroller
1class CommentsController < ApplicationController 2 def create 3 Comment.create(comment_params) 4 redirect_to root_path #ここの記述は勉強し直し! 5 end 6 7 private 8 def comment_params 9 params.require(:comment).permit(:text, :image).merge(user_id: current_user.id, post_id: params[:post_id]) 10 end 11end
postcontroller
1class PostsController < ApplicationController 2 3 def index 4 @posts = Post.all 5 end 6 7 def new 8 @post = Post.new 9 end 10 11 12 def create 13 Post.create(post_params) 14 redirect_to root_path 15 end 16 17 18 def show 19 @post = Post.find(params[:id]) 20 @comment = Comment.new 21 @comments = @post.comments.includes(:user) 22 end 23 24 25 def edit 26 @post = Post.find(params[:id]) 27 end 28 29 def update 30 @post = Post.find(params[:id]) 31 @post.update(post_params) 32 redirect_to root_path 33 end 34 35 def destroy 36 @post = Post.find(params[:id]) 37 @post.destroy 38 redirect_to root_path 39 end 40 41 42 private 43 def post_params 44 params.require(:post).permit(:title, :image, :subtitle, :content) 45 end 46 47 48end 49
次の記述でトップページにpostについたコメントを表示したい
と思ったのですが、エラーです。
index
1.comment-square 2 - @post.comments.each do |comment| 3 .comment-content 4 = comment.text
試したこと
postコントローラーのindexに記述を加えました。
def index @posts = Post.all @post = Post.find(params[:id]) end
def index @posts = Post.all @comments = @post.comments.includes(:user) end
など試しているのですが、上手くできません。
何かヒントをいただけたら幸いです。
postテーブルにcomment_idを取得する必要などがあるのでしょうか?
回答1件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2020/01/27 23:01
2020/01/28 03:24
2020/01/28 06:33