首页 > 解决方案 > 类型错误:评论未定义

问题描述

我想在生产环境中运行的 Rails 5.1.4 应用程序中使用 JavaScript 和 rails-ujs 通过 AJAX 提交新评论,数据库 Postgres 11(没有部署)

(这适用于开发环境)

但是当我尝试发表新评论时,我的观点并没有改变,我web-console收到了这个:

TypeError: Comments is undefined在我的 create.js.erb 文件中引用第 9 行

创建.js.erb

var comment = {
  'body': '<%= @comment.body %>',
  'commenter': '<%= @comment.user.name %> ',
  'commenterId': '<%= @comment.user.id %> ',
  'avatar': '<%= @comment.user.avatar %> ',
  'datetime': '<%= @comment.created_at.strftime('on %e %b %Y at %H:%M') %>',
};

Comments.displayComment(comment);     # <~ Line causing the error

console.log("Comment", comment);

提取的comments.js

Comments = {};

Comments.displayComment = function(comment) {

  var commentBlock = document.createElement('blockquote');
  commentBlock.className = 'blockquote';

  ...
  ...
  ...

  var comments = document.getElementById('commentList');
  comments.appendChild(commentBlock);
};

提取的显示视图(设置远程:true)

<%= form_for([@tip, @tip.comments.build], remote: true) do |form| %>

我一直在查看其他帖子以寻找类似的答案,但还没有运气。另外,我尝试在create.js.erb文件中声明一个变量“评论”,但收到了同样的错误。

我想我在我的 javascript 中遗漏了一些东西,但我不确定是什么。任何帮助,将不胜感激。谢谢。

标签: javascriptruby-on-railsajaxpostgresqlproduction-environment

解决方案


这些是我解决它的步骤:

在我的中,我发现与文件production.log有冲突。bootstrap.js所以,我提前删除了它。

  1. 删除文件public/assets中的所有文件。(删除之前的预编译)
  2. 清空/my_rails_app/tmp文件夹(清除由 rails 创建的临时文件)
  3. 运行 RAILS_ENV=production rails assets:precompile(预编译我的资产管道)
  4. RAILS_ENV=production rails server在您的Terminal( bash/shell)上运行。或者只是运行 ./run-my-production.sh文件(在生产环境中重新启动服务器)。这里是run-production.sh文件的示例
  5. 访问您的https://localhost:3000 并重试:我的 AJAX 调用按预期正常工作。

干杯。


推荐阅读