NoMethodError(nil的未定义方法`fetch':NilClass)

时间:2017-09-24 11:06:33

标签: ruby-on-rails websocket actioncable

问题在于使用ActionCable通过Web套接字广播数据。该错误似乎表明它来自create方法。

错误消息

 Rendered weight/_weight.html.erb (1.1ms)
 [ActionCable] Broadcasting to weight: "<div class=\"row\">\n  <div class=\"col-md-8 well\">\n    <p>12.0 kg</p>\n    <small>less than a minute</small>\n  </div>\n</div>"
Completed 500 Internal Server Error in 25ms (Views: 7.4ms | ActiveRecord: 10.6ms)



NoMethodError (undefined method `fetch' for nil:NilClass):

app/controllers/weight_controller.rb:7:in `create'
Rendering /usr/local/rvm/gems/ruby-2.3.4/gems/actionpack-5.0.4/lib/action_dispatch/middleware/templates/rescues/diagnostics.text.erb
Rendering /usr/local/rvm/gems/ruby-2.3.4/gems/actionpack-5.0.4/lib/action_dispatch/middleware/templates/rescues/_source.text.erb
Rendered /usr/local/rvm/gems/ruby-2.3.4/gems/actionpack-5.0.4/lib/action_dispatch/middleware/templates/rescues/_source.text.erb (0.8ms)
Rendering /usr/local/rvm/gems/ruby-2.3.4/gems/actionpack-5.0.4/lib/action_dispatch/middleware/templates/rescues/_trace.text.erb
Rendered /usr/local/rvm/gems/ruby-2.3.4/gems/actionpack-5.0.4/lib/action_dispatch/middleware/templates/rescues/_trace.text.erb (0.9ms)
Rendering /usr/local/rvm/gems/ruby-2.3.4/gems/actionpack-5.0.4/lib/action_dispatch/middleware/templates/rescues/_request_and_response.text.erb
Rendered /usr/local/rvm/gems/ruby-2.3.4/gems/actionpack-5.0.4/lib/action_dispatch/middleware/templates/rescues/_request_and_response.text.erb (1.1ms)
Rendered /usr/local/rvm/gems/ruby-2.3.4/gems/actionpack-5.0.4/lib/action_dispatch/middleware/templates/rescues/diagnostics.text.erb (25.0ms)

从controller.rb创建方法

def create
   @weight = Weight.new(weight_params)
   @weight.user_id = current_user.id
    if @weight.save
        ActionCable.server.broadcast "weight", render(partial: 'weight/weight', object: @weight)

    else
        flash[:danger] = "New Weight was not added!"
        redirect_to current_user
    end
end

private

def weight_params
    params.require(:weights).permit(:weight)
end

我只是无法确定返回的内容为零。信息在正确广播中的正确性这一事实是正确的,这表明它已将其正确地保存到数据库中。无法想象它还在执行'fetch'方法。

非常确定Web套接字已正确设置。见下文。

config / application.rb:

config.action_cable.mount_path = '/cable'

config / routes.rb:

mount ActionCable.server => '/cable'

weight_channel.rb:

def subscribed
  stream_from "weight"
end

weight.coffee:

 received: (data) -> 
    $("#messages").prepend(data)

1 个答案:

答案 0 :(得分:0)

由于缺少config/cable.yml文件而引发错误。

解决方案是使用具有应用程序所需设置的config/cable.yml。即:

# Action Cable uses Redis by default to administer connections, channels, and sending/receiving messages over the WebSocket.
production:
  adapter: redis
  url: redis://localhost:6379/1

development:
  adapter: redis
  url: redis://localhost:6379/1

staging:
  adapter: redis
  url: redis://localhost:6379/1

test:
  adapter: async

该决议出现在问题的评论中。