首页 > 解决方案 > 评论未保存到数据库 - 无法自动加载常量 CommentController

问题描述

我正在 RoR 中构建一个论坛应用程序,目前我无法在数据库中保存评论。

当按下“创建评论”按钮时,终端上会出现以下错误:

LoadError(无法自动加载常量 CommentController,需要 /..//app/controllers/comment_controller.rb 来定义它)

这是我的路线:

devise_for :users
root                              to: 'post#index'

#Posts
get    '/posts/new',             to: 'post#new' 
get    '/post/:id',              to: 'post#show',      as: 'show'
get    '/post/:id/edit',         to: 'post#edit',      as: 'edit'
post   '/post',                  to: 'post#create'
put    '/post/:id',              to: 'post#update',    as: 'update'
delete '/post/:id',              to: 'post#destroy',   as: 'delete' 

#Comments
post  '/post/:post_id',  to: 'comment#create', as: 'new_comments'

comment_controller.rb:

class CommentsController < ApplicationController
  before_action :set_comment, only: [:show, :edit, :update, :destroy]
  before_action :authenticate_user! 

  def index
    @comments = Comment.all
  end

  def new
    @comment = Comment.new
  end

  def create 
    @post = Post.find(params[:post_id])
    @comment = @post.comments.new(comment_params)
    @comment.user = current_user
    @comment.assign_attributes(comment_params)


      if @comment.save
        format.html { redirect_to @link, notice: 'Comment was successfully created.' }
        format.json { render json: @comment, status: :created, location: @comment }
      else
        format.html { render action: "new" }
        format.json { render json: @comment.errors, status: :unprocessable_entity }
      end


  end

  def destroy
    @comment.destroy
    respond_to do |format|
      format.html { redirect_to :back, notice: 'Comment was successfully destroyed.' }
      format.json { head :no_content }
    end
  end

  private
    # Use callbacks to share common setup or constraints between actions.
    def set_comment
      @comment = Comment.find(params[:id])
    end

    # Never trust parameters from the scary internet, only allow the white list through.
    def comment_params
      params.require(:comment).permit(:post_id, :content, :title, :user_id)
    end


end

html表单:

<div id="comments-form">
 <%= form_for @comment, url: new_comments_path(@post), method: :post, remote: true do |f| %>
    <%= f.label :title %><br>
    <%= f.text_field :title, placeholder: "Type the comment title here" %><br>
    <%= f.label :content %><br>
    <%= f.text_area :content, placeholder: "Type the comment content here" %><br>
  <%= f.submit %>
<% end %>

以及帖子和评论模型。

邮政:

class Post < ApplicationRecord
    belongs_to :user
    has_many :comments
    validates :title, :content, presence: true
end

评论:

class Comment < ApplicationRecord
    belongs_to :user
    belongs_to :post
    has_many :reviews
end

谢谢您的帮助。

标签: ruby-on-railsruby

解决方案


刚刚发现错误,我错误地定义了控制器类。

它应该读类CommentController < ApplicationController而不是类

CommentsController < ApplicationController

推荐阅读