nil:NilClass

时间:2019-11-21 14:11:06

标签: ruby-on-rails vue.js mongoid

我正在完成我的第一个项目,将ruby放在api上,将vuejs用作前端,将mongodb用作DB,所以我正在使用mongoid。

调用控制器的get方法时出现问题。控制台错误是nil:NilClass的未定义方法'messages',但是当我尝试 puts @ message.inspect 时,它会获取房间中所有应获取的消息,因此在这一点上还可以。我不知道错误在哪里,如果在查询完成之前。

message_controller.rb

class MessagesController < ApplicationController
  before_action :authorize_access_request!
  before_action :set_sala

  def index
    @message = @sala.messages
    puts @message.inspect
    render json: @message
  end

  private

    def set_sala
      if params[:sala_id]
        @sala = Sala.find(params[:sala_id])
      end
    end
end

模型消息

class Message
  include Mongoid::Document
  include Mongoid::Timestamps::Created

  field :body, type: String

  belongs_to :usuario, foreign_key: :usuario_id
  belongs_to :sala, foreign_key: :sala_id

end

萨拉模型

class Sala
  include Mongoid::Document

  field :nombre, type: String

  belongs_to :usuario
  has_many :messages

end

终端

Started POST "/sala/messages" for 127.0.0.1 at 2019-11-21 15:06:01 +0100
Processing by MessagesController#index as HTML
Parameters: {"sala_id"=>"5dd66a5f575e22274d0a5578", "message"=> {"sala_id"=>"5dd66a5f575e22274d0a5578"}}
MONGODB | [55] localhost:27017 #1 | prueba2_backend_development.find | STARTED | {"find"=>"salas", "filter"=>{"_id"=>BSON::ObjectId('5dd66a5f575e22274d0a5578')}}
MONGODB | [55] localhost:27017 | prueba2_backend_development.find | SUCCEEDED | 0.001s
MONGODB | [56] localhost:27017 #1 | prueba2_backend_development.find | STARTED | {"find"=>"messages", "filter"=>{"sala_id"=>BSON::ObjectId('5dd66a5f575e22274d0a5578')}}
Started GET "/messages" for 127.0.0.1 at 2019-11-21 15:06:01 +0100
MONGODB | [56] localhost:27017 | prueba2_backend_development.find | SUCCEEDED | 0.001s
Processing by MessagesController#index as HTML
[#<Message _id: 5dd69592575e221a9e751c0d, created_at: 2019-11-21 13:48:02 UTC, body: "Mensaje 1", usuario_id: BSON::ObjectId('5dc9b447575e2237b9205299'), sala_id: BSON::ObjectId('5dd66a5f575e22274d0a5578')>, #<Message _id: 5dd695d9575e221a9e751c0e, created_at: 2019-11-21 13:49:13 UTC, body: "Sale aqui ", usuario_id: BSON::ObjectId('5dc9b447575e2237b9205299'), sala_id: BSON::ObjectId('5dd66a5f575e22274d0a5578')>]
Completed 200 OK in 8ms (Views: 0.7ms | MongoDB: 0.0ms | Allocations: 2712)


Completed 500 Internal Server Error in 2ms (MongoDB: 0.0ms | Allocations: 857)

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

app/controllers/messages_controller.rb:7:in `index'

1 个答案:

答案 0 :(得分:1)

由于@sala为nil,而您正试图在nil对象上调用messages,因此收到错误消息。

如果我们查看您的控制器代码,则会在@sala中设置set_sala,该params[:sala_id]在每次操作之前都会被调用。查看您的逻辑,如果不存在@sala,那么将不会设置GET

请注意您的Started GET "/messages" for 127.0.0.1 at 2019-11-21 15:06:01 +0100请求-sala_id-参数setTimeout()不存在,因此出错。