我正在尝试为特定帖子创建评论,当我点击评论时,我得到未初始化的常量尖叫声...我确实有路线
class Squeal < ActiveRecord::Base
has_many :comments, as: :commentable
end
class Comment < ActiveRecord::Base
belongs_to:commentable, polymorphic:true
end
class Squeals::CommentsController <CommentsController
before_action :set_commentable
private
def set_commentable
@commentable = Squeal.find(params[:squeal_id])
end
end
class CommentsController < ApplicationController
before_action:authenticate_user!
def create
@comment = @commentable.comments.new comment_params
@user.user = current_user
comment.save
redirect_to @commentable, notice: "Your comment was posted"
end
private
def comment_params
params.require(:comment).permit(:body)
end
end
resources :squeals do
resources :comments, module: :squeals
end
答案 0 :(得分:1)
在这一行:
class Squeals::CommentsController <CommentsController
您将CommentsController
嵌套在Squeals
课程中,您尚未在任何地方定义。
如果您改为这样做,如果您将文件保存在app/controllers/squeals/comments_controller.rb
(由于Rails自动加载代码的方式,这可能是必要的),它会起作用。
class Squeals
class CommentsController < ApplicationController
...
end
end
用于创建嵌套类的单行语法要求父项已存在。
答案 1 :(得分:1)
更改
comment.save to @comment.save
或者尝试在Gemfile中安装pry gem
gem 'pry'
并调试代码。
答案 2 :(得分:1)
大家好,我不再通过以下方式解决了多态性评论:
def create
@post = Squeal.find(params[:squeal_id])
@comment = @post.comments.create(comment_params)
if @comment.save
redirect_to @post
else
flash.now[:danger] = "error"
end
end
resources :squeals do
resources :comments
end