ruby-on-rails - 评论未保存到数据库 - 无法自动加载常量 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
谢谢您的帮助。
解决方案
刚刚发现错误,我错误地定义了控制器类。
它应该读类CommentController < ApplicationController
而不是类
CommentsController < ApplicationController
推荐阅读
- python - python中的套接字连接被拒绝错误
- python - 包括您在 re.findall 中拆分的文本
- javascript - 如何在 Electron 中通过 preload.js 请求模块
- laravel - 在 Vue 中对 prop 的多个方面使用 .includes 来构建搜索
- azure-data-factory - 如何在数据工厂中创建 Azure Data Lake Storage Gen 2 类型的数据集?
- terraform - terraform 根据条件选择资源
- c++ - C++ 使用模板专门化一个类模板
- nginx - 一个位置内的 nginx 行排序是否重要?
- kubernetes - 一个或多个容器没有资源限制 - VS Code Kubernetes 工具中的警告
- heroku - 如何将 Heroku ClearDB 连接到 MySQL Workbench?