nil:NilClass的未定义方法'messages'>>

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

我正在完成我的第一个项目,其中将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

Sala模型

class Sala
  include Mongoid::Document

  field :nombre, type: String

  belongs_to :usuario
  has_many :messages

end

Terminal

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'

我正在完成我的第一个项目,其中ruby在api上,vuejs在前端,mongodb在DB上,所以我正在使用mongoid。当我调用控制器的get方法时出现问题。控制台错误是...

ruby-on-rails vue.js mongoid
1个回答
0
投票

由于@sala为nil,而您试图在nil对象上调用messages,因此出现错误。

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

© www.soinside.com 2019 - 2024. All rights reserved.