使用Rails5和Actioncable实现实时更新的问题

时间:2017-02-13 02:54:38

标签: ruby websocket real-time ruby-on-rails-5 actioncable

我正在尝试使用动作电缆实现一个简单的rails fullstack todo应用程序。 不幸的是,有关动作电缆的文档仍然让我感到困惑。 我试图参考DHH的示例和https://blog.heroku.com/real_time_rails_implementing_websockets_in_rails_5_with_action_cable并调整到我的应用https://github.com/tenzan/rails-fullstack-todo

当我使用一个浏览器创建任务时,它不会在http://localhost:3000/tasks显示实时更新,而另一个浏览器会自动更新。

我的环境:

  1. Mac OS X Sierra
  2. Rails 5.0.0.1
  3. Ruby 2.4.0
  4. 在Gemfile中启用Redis并在端口6379
  5. 上运行
  6. RethinkDB
  7. 我实施了:

    应用/资产/ Javascript角/信道/ index.coffee

    //= require cable
    //= require_self
    //= require_tree .
    
    this.App = {};
    
    App.cable = ActionCable.createConsumer();  
    

    应用/资产/ Javascript角/信道/ tasks.js

    App.tasks = App.cable.subscriptions.create('TasksChannel', {
      received: function(data) {
        $("#tasks").removeClass('hidden')
        return $('#tasks').append(this.renderTask(data));
      }
    });
    

    应用/信道/ tasks_channel.rb

    class TasksChannel < ApplicationCable::Channel
      def subscribed
        stream_from "tasks"
      end
    
      def unsubscribed
        # Any cleanup needed when channel is unsubscribed
      end
    

    应用/控制器/ tasks_controller.rb

      def create
        @task = Task.new(task_params)
    
        respond_to do |format|
          if @task.save
            ActionCable.server.broadcast 'tasks', task: @task.title
            format.html { redirect_to tasks_url, notice: 'Task was successfully created.' }
            format.json { render :show, status: :created, location: @task }
          else
            format.html { render :new }
            format.json { render json: @task.errors, status: :unprocessable_entity }
          end
        end
      end
    

    app / views / layouts / application.html.erb :已添加<%= action_cable_meta_tag %>

    配置/ cable.yml

    local: &local
      url: redis://localhost:6379
    
    development: *local
    test: *local
    

    配置/环境/ development.rb

    Rails.application.configure do
      config.action_cable.url = "ws://localhost:3000/cable"
    

    配置/ routes.rb中

    Rails.application.routes.draw do
      mount ActionCable.server => '/cable'
    

    应用/视图/任务/ index.html.erb

                                             

    我怀疑

    有问题
    1. app/assets/javascripts/channels/tasks.coffee
    2. app/views/tasks/index.html.erb
    3. 但我真的不知道如何修复/调整它们。

0 个答案:

没有答案