在资产预编译期间访问数据库/模型对象

问题描述 投票:0回答:1

我正在尝试将Rails聊天应用程序部署到Heroku,但是我的JavaScript无法在资产预编译期间调用数据库。推送失败,并显示“预编译资产失败。”

跟踪后,我发现

remote:        Caused by:
remote:        PG::UndefinedTable: ERROR:  relation "chatrooms" does not exist
remote:        LINE 1: SELECT "chatrooms".* FROM "chatrooms"

经过一番调查,我发现Chatroom.all.each是引起麻烦的原因。

频道(客户端):

// my-app/app/assets/javascripts/channels/chatroom.js.erb

//Iterate through chatrooms
<% Chatroom.all.each do |chatroom| %>

  App['chatroom' + <%= chatroom.id %>] = App.cable.subscriptions.create({channel: "ChatroomChannel", room: <%= chatroom.id %>},{    

      received: function(data) {
          ...
      };

  });

<% end %>

所以我似乎在预编译期间无法访问Chatroom模型。我需要在production.rb文件中添加一些内容吗?该应用程序在我的本地环境中可以正常运行。

ruby-on-rails postgresql heroku
1个回答
0
投票

似乎在资产预编译时无法访问数据库。

我通过将聊天室ID存储在HTML5数据属性中,并使用jQuery对其进行迭代来解决此问题。

// my-app/app/assets/javascripts/channels/chatroom.js.erb

$(document).on('turbolinks:load', () => {

  //Iterate through chatrooms
  $('.message-container').each(function() {

    App[`chatroom${$(this).data('chatroom_id')}`] = App.cable.subscriptions.create({channel: "ChatroomChannel", room: String($(this).data('chatroom_id'))},{

      received: function(data) {
        ...
      }

    });
  });
})
© www.soinside.com 2019 - 2024. All rights reserved.