【问题标题】:How to add comments如何添加评论
【发布时间】:2013-06-07 14:02:36
【问题描述】:

我正在尝试将 cmets 添加到后期模型。到目前为止,这是我的 cmets_controller:

class CommentsController < ApplicationController

    before_action :find_post

    def index
        @comments = @post.comments.order('id')
    end

    def new
        @comment = @post.comments.new
    end

    def create
        @comment = @post.comments.build(params[:comment])
        @comment.user = current_user
        @comment.save
        redirect_to post_path(@post)
    end

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

    def find_post
        @user = current_user
        @post = @user.posts.find(params[:post_id])
    end
end

我得到这个错误:

NoMethodError in CommentsController#new undefined method `posts' for nil:NilClass

如您所见,我是编程新手。感谢您的帮助!:)

【问题讨论】:

    标签: ruby-on-rails ruby ruby-on-rails-4


    【解决方案1】:

    您未登录时可能会遇到错误。由于before_action :find_post,每次都会调用方法find_post。如果您未登录,则current_usernil,您调用postsnil

    【讨论】:

      猜你喜欢
      • 2014-07-06
      • 1970-01-01
      • 2021-01-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多