Home > Back-end >  NoMethodError in Comments#new
NoMethodError in Comments#new

Time:11-16

class CommentsController < ApplicationController
  def new
    @post = Post.find_by_id(params[:post_params])
    @comment = Comment.new
  end

  def create
    @post = Post.find(params[:post_params])  
    @post_id = current_user.id
   # @post_id = @post.post.id
    @comment = @post.comments.new(comment_params)
    @post.user_id = current_user

    @comment  = current_user
    if @comment.save
      redirect_to root_path
    else
      render :new 
    end
  end  

  private

  def comment_params        
   enter code hereparams.require(:comment).permit(:message, :post_id)
  end
end   

CodePudding user response:

give a rake routes | grep comments#new or rails routes | grep comments#new to find the route definition. It's probably nested in the post resources' routes and you have :post_id in its path. So you should change to

def new
  @post = Post.find_by_id(params[:post_id])
  @comment = Comment.new
end

CodePudding user response:

If you want to create a nested record you would do:

resources :posts do
  resources :comments, only: [:new, :create]
end
class Post < ApplicationRecord
  # ...
  has_many :comments
end
class Comment< ApplicationRecord
  # ...
  belongs_to :user
  belongs_to :post
end
class CommentsController < ApplicationController
  before_action :set_post, only: [:new, :create]

  # GET /posts/1/comments
  # You probally don't even need this if you have a form 
  # on the bottom the posts show view
  def new
    @comment = @post.comments.new
  end

  # POST /posts/1/comments
  def create
    # this was complete gibberish
    @comment = @post.comments.new(comment_params) do |c|
      c.user = current_user
    end
    if @comment.save
      redirect_to @post, 
        notice: 'Comment created'
    else
      render :new 
    end
  end  

  private

  def set_post
    # use find in instead of find_by_id as it will raise 
    # if the record is not found 
    @post = Post.find(params[:post_id])
  end

  def comment_params        
    # this was completely mangled
    # you also don't need 
    params.require(:comment)
          .permit(:message)
  end
end  

Solving problems by just throwing random code at them you don't understand doesn't actually work as a learning method. For example you left enter code here in there which means you are calling this in your comment_params which is causing the the error - or at least some of them:

enter(code(hereparams.require(:comment).permit(:message, :post_id)))

You're also assigning and reassigning a bunch of instance variables in a jumble to the point where you're actually breaking the method with @comment = current_user so when you call @comment.save in the next you're actually updating the user instead of saving the comment.

  • Related