【问题标题】:Can't figure out why I am getting unititalized constants error无法弄清楚为什么我会收到 unititalized constants 错误
【发布时间】:2017-06-15 02:37:25
【问题描述】:

我正在尝试为特定帖子创建评论,当我点击评论时,我得到未初始化的常量 Squeals.. 我确实有路线

SQUEAL 模型

class Squeal < ActiveRecord::Base
  has_many :comments, as: :commentable
end

comment.rb

class Comment < ActiveRecord::Base
  belongs_to:commentable, polymorphic:true
end

/squeal/cmets_controller.rb

class Squeals::CommentsController <CommentsController
  before_action :set_commentable

  private
  def set_commentable
    @commentable = Squeal.find(params[:squeal_id])
  end

end

cmets 控制器

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

squeal/show.html.erb

【问题讨论】:

  • 我们可以看看确切的错误日志输出吗?

标签: ruby-on-rails ruby


【解决方案1】:

大家好,我不再使用多态 cmets 我通过执行以下操作来解决它:

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

【讨论】:

    【解决方案2】:

    改变

    comment.save to @comment.save
    

    或者尝试在 Gemfile 中安装 pry gem

    gem 'pry'
    

    并调试代码。

    【讨论】:

      【解决方案3】:

      在这一行:

      class Squeals::CommentsController <CommentsController
      

      您将 CommentsController 嵌套在您尚未在任何地方定义的 Squeals 类中。

      如果你这样做,如果你将文件保存在app/controllers/squeals/comments_controller.rb 就可以了(这可能是必要的,因为 Rails 自动加载代码的方式)

      class Squeals
        class CommentsController < ApplicationController
          ...
        end
      end
      

      创建嵌套类的单行语法要求父类已经存在。

      【讨论】:

      • 我稍后会删除答案。也许尝试将类尖叫定义放入 config/initializers
      • 我不会使用多态 cmets ...我在 cmets 控制器上执行此操作,而不是我注释掉的内容...
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-11-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-07-28
      • 1970-01-01
      相关资源
      最近更新 更多