nil:NilClass 的未定义方法“消息”

undefined method `messages' for nil:NilClass

我的第一个项目是 ruby 在 rails 上作为 api,vuejs 作为前端,mongodb 作为数据库,所以我正在使用 mongoid .

当我调用我的控制器的 get 方法时,我的问题出现了。控制台错误是 undefined method `messages' for nil:NilClass,但是当我尝试 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'

您收到错误消息是因为 @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 不存在,因此出现错误。