当前位置: 首页 > 知识库问答 >
问题:

Rails无法为nil:NilClass呈现JSON未定义的方法“new”

羊舌洛华
2023-03-14

我正在开发一个Rails应用程序,它有两个名称空间,分别是用于管理员的admin和用于移动设备的api

昨天发生了一件奇怪的事。我在我的PostgreSQL数据库中创建了一个新表,由id、name、created\u at、Update\u at组成。

我试图使用名称空间获取所有设施http://localhost:3000/admin/facilities它运行良好(返回HTML和工具列表)。

Started GET "/admin/facilities" for ::1 at 2015-05-10 16:12:47 +0800
Processing by Admin::FacilitiesController#index as HTML
  Facility Load (0.4ms)  SELECT "facilities".* FROM "facilities"
  Rendered admin/facilities/index.html.erb within layouts/application (2.5ms)
Completed 200 OK in 91ms (Views: 90.4ms | ActiveRecord: 0.4ms)

但是当我打电话的时候http://localhost:3000/api/v1/facilities来自浏览器,它应该返回JSON。我出错了

在Api::V1::FacilitiesController#索引未定义的方法'new'为零:NilClass

Extracted source (around line #8):
6  def index
7    @facilities = Facility.all
8    render json: @facilities
9  end
10
11

来自控制台的错误

Started GET "/api/v1/facilities" for ::1 at 2015-05-10 16:38:26 +0800
Processing by Api::V1::FacilitiesController#index as HTML
  User Load (0.6ms)  SELECT  "users".* FROM "users" WHERE "users"."id" IS NULL  ORDER BY "users"."id" ASC LIMIT 1
  Facility Load (0.5ms)  SELECT "facilities".* FROM "facilities"
Completed 500 Internal Server Error in 6ms (ActiveRecord: 1.1ms)

NoMethodError (undefined method `new' for nil:NilClass):
  app/controllers/api/v1/facilities_controller.rb:8:in `index'


  Rendered /Users/abrahamks/.rvm/gems/ruby-2.2.1/gems/actionpack-4.2.1/lib/action_dispatch/middleware/templates/rescues/_source.erb (7.1ms)
  Rendered /Users/abrahamks/.rvm/gems/ruby-2.2.1/gems/actionpack-4.2.1/lib/action_dispatch/middleware/templates/rescues/_trace.html.erb (2.7ms)
. . . .
. . . .
and so on

我从rails c检查并调用设施。看起来命令行返回了正确的值,但我不理解为什么它不能呈现/返回json。

Loading development environment (Rails 4.2.1)
2.2.1 :001 > Facility.all
  Facility Load (0.5ms)  SELECT "facilities".* FROM "facilities"
 => #<ActiveRecord::Relation [#<Facility id: 1, name: "Kitchen", created_at: "2015-05-09 10:54:00", updated_at: "2015-05-09 16:08:48">, #<Facility id: 2, name: "Washer", created_at: "2015-05-09 11:20:40", updated_at: "2015-05-09 16:09:32">, #<Facility id: 3, name: "Swimming Pool", created_at: "2015-05-09 11:22:19", updated_at: "2015-05-09 16:09:41">, #<Facility id: 4, name: "Internet", created_at: "2015-05-09 11:24:02", updated_at: "2015-05-09 16:12:31">, #<Facility id: 5, name: "Dryer", created_at: "2015-05-09 15:55:36", updated_at: "2015-05-09 16:12:54">]> 

我的代码怎么了?有没有我错过的配置?非常感谢。




#GET/facilities/1设施与属性有多对多关系,我生成一个连接表

class CreateJoinTablePropertiesFacilities < ActiveRecord::Migration
  def change
    create_join_table :properties, :facilities do |t|
      t.index [:property_id, :facility_id]
      t.index [:facility_id, :property_id]
    end
  end
end

这是我的设备。rb

class Facility < ActiveRecord::Base
    has_and_belongs_to_many :property, join_table: :facilites_properties
end

这是我的routes.rb

Rails.application.routes.draw do
  namespace :admin do
    resources :facilities
  end

  namespace :api do
    namespace :v1 do
      resources :properties
      resources :facilities, only: [:index, :show]
      resources :users do
        member do
        post 'list', :to => "users#list_property"
    end
  end

这是我的应用程序/控制器/api/v1/facilities\u控制器

class Api::V1::FacilitiesController < ApplicationController
  before_action :set_facility, only: [:show, :edit, :update, :destroy]
  # before_action :authenticate
  # GET /facilities
  # GET /facilities.json
  def index
    @facilities = Facility.all
    render json: @facilities
  end

  # GET /facilities/1
  # GET /facilities/1.json
  def show
    render json: @facility
  end

  private
    # Use callbacks to share common setup or constraints between actions.
    def set_facility
      @facility = Facility.find(params[:id])
    end

    # Never trust parameters from the scary internet, only allow the white list through.
    def facility_params
      params.require(:facility).permit(:name)
    end
end

这是app/controllers/admin/facilities\u controller

class Admin::FacilitiesController < ApplicationController
  before_action :set_facility, only: [:show, :edit, :update, :destroy]
  # before_action :authenticate
  # GET /facilities
  # GET /facilities.json
  def index
    @facilities = Facility.all
  end

  # GET /facilities/1
  # GET /facilities/1.json
  def show
  end

  # GET /facilities/new
  def new
    @facility = Facility.new
  end

  # GET /facilities/1/edit
  def edit
  end

  # POST /facilities
  # POST /facilities.json
  def create
    @facility = Facility.new(facility_params)

    respond_to do |format|
      if @facility.save
        format.html { redirect_to admin_facilities_path, notice: 'Facility was successfully created.' }
        format.json { render :show, status: :created, location: @facility }
      else
        format.html { render :new }
        format.json { render json: @facility.errors, status: :unprocessable_entity }
      end
    end
  end

  # PATCH/PUT /facilities/1
  # PATCH/PUT /facilities/1.json
  def update
    respond_to do |format|
      if @facility.update(facility_params)
        format.html { redirect_to admin_facilities_path, notice: 'Facility was successfully updated.' }
        format.json { render :show, status: :ok, location: @facility }
      else
        format.html { render :edit }
        format.json { render json: @facility.errors, status: :unprocessable_entity }
      end
    end
  end

  # DELETE /facilities/1
  # DELETE /facilities/1.json
  def destroy
    @facility.destroy
    respond_to do |format|
      format.html { redirect_to facilities_url, notice: 'Facility was successfully destroyed.' }
      format.json { head :no_content }
    end
  end

  private
    # Use callbacks to share common setup or constraints between actions.
    def set_facility
      @facility = Facility.find(params[:id])
    end

    # Never trust parameters from the scary internet, only allow the white list through.
    def facility_params
      params.require(:facility).permit(:name)
    end
end

共有2个答案

端木夕
2023-03-14

我刚刚意识到我忘了生成序列化程序。因为我使用gem活动模型序列化程序,所以这就是我生成序列化程序所做的。

rails g序列化工具

翟黎明
2023-03-14

堆栈跟踪显示请求已作为HTML处理。

Processing by Admin::FacilitiesController#index as HTML

当您试图呈现JSON时,您可以指定控制器来响应JSON

module Api
  module V1
    class FacilitiesController < ApplicationController
      respond_to :json
    end
  end
end

或者可以在路由中指定json作为默认响应。rb文件

namespace :api, defaults: { format: 'json' }  do
  # your api json routes...
end

希望其中任何一个有帮助。

 类似资料:
  • 超过3个小时,我试图解决相当容易的错误(第一眼): 但还是没有成功。 我有DB表products,其中包含列category\u id和manufacturer\u id。 协会: 试图获取一些数据: 我获取了所有行,其中在列

  • 背景:我是一个自动化新手,我正在尝试使用红宝石和硒进行一些测试。我对自己在做什么有一些了解,但我仍然很新手。 问题:当尝试调用应该从页面部分继承该方法的对象上的方法时,我得到了一个“nil: nilclass的nomethoderror未定义方法”。 故障排除和研究:我搜索了nil:nilclass问题的类似问题,但找不到任何真正符合我尝试做的事情(或者在我的noob眼里不是这样)。我怀疑我没有正

  • Rails关联的基本问题如下表: 商店:名称,网络 产品:标题、价格、店铺id 关系定义为has_many并属于: 型号: shop.rb 产品rb型 控制器: shops\u控制器。rb型 products_controller.rb 在商店视图中,我设法参考并显示每个商店的所有产品,没有问题: 但另一方面,在产品视图中,我无法从Shop表中显示网络信息: 这将返回以下错误:

  • 我尝试在Rails中编写Rspec测试,使用Desive助手方法进行登录和注销。“登录”方法不起作用。然而,在对应用程序进行大量更改之前,它就已经开始工作了。 我尝试过的事情: 我将测试助手包括在Rspec中。配置 使用典狱长的登录名作为 正在清除Rails缓存 除掉水豚,看看是否是水豚引起的问题 我没有在控制器规范中明确设置会话(例如,没有有效的\u会话) 到目前为止,没有骰子。使用已登录用户测

  • Good day我不确定发生了什么我怀疑eclipse,但在UserDetailsServiceImpl中它是定义的,因为我实现了spring的UserDetails服务,下面是我的代码 这是让人头痛的一行“UserDetails UserDetails=userDetailsService.loadUserByUsername(username)”提前感谢您

  • 我试过在本地迁移,然后推到heroku它没有工作。我尝试过heroku run rake DB:Migrate,然后重新启动它不起作用。 我试着重新启动dyno,它也没有工作。 有什么我可以查一下的可以提供更多的细节吗?我正在查看heroku run rake db:migrate:status,但它只显示了一般的迁移创建书籍。 Controllers/Books_Controller.rb