首页 > 解决方案 > Rails(对象不支持#inspect)/ NoMethodError(nil:NilClass 的未定义方法“[]”)

问题描述

我有一个模型“部分”。每当我尝试迭代 Section 对象时,例如“Section.all”或“Section.create”,我在 Rails 控制台和“NoMethodError(未定义方法 `[] ' for nil:NilClass)" 在终端中。

红宝石:红宝石 2.6.1p33

导轨:5.2.3

部分迁移

class CreateSections < ActiveRecord::Migration[5.2]
  def change
    create_table :sections do |t|
      t.string :name
      t.integer :students_count, :default => 0
      t.references :class, index: true
      t.references :class_teacher, index: true

      t.timestamps
    end
    add_foreign_key :sections, :standards, column: :class_id
    add_foreign_key :sections, :users, column: :class_teacher_id
  end
end

剖面模型

class Section < ApplicationRecord
  belongs_to :class, :class_name => "Standard", :foreign_key => "standard_id"
  belongs_to :class_teacher, :class_name => "User", :foreign_key => "class_teacher_id"
end

控制器代码

def index
  @sections = Section.where(:class_id => params[:class_id])

  render json: @sections
end

终端输出

NoMethodError (undefined method `[]' for nil:NilClass):

Rails 控制台输入

Section.all

Rails 控制台输出

(Object doesn't support #inspect)

奇怪的是,当 Section 表为空时,控制台输出为

#<ActiveRecord::Relation []> 

标签: ruby-on-rails

解决方案


除了@Tom Lord 的评论,您还必须更正关联:

class Section < ApplicationRecord
  belongs_to :class, class_name: "Standard"                    
  belongs_to :class_teacher, class_name: "User"
end

由于您的迁移为引用创建了一个class_idclass_teacher_id,因此正确的 FK 名称就是那些。

您需要在 has_many 模型上设置 FK:

class Standard < ApplicationRecord
  has_many :sections, foreign_key: :class_id
end

更新:FK 总是在belongs_to表上创建。由于您设置的关联是 named class,Rails 期望class_id在表上出现一个名为的列,它有,这就是您不需要在belongs_to模型中设置 FK 的原因。

另一方面,Rails 无法推断has_many模型中的 FK,因为它需要在 table 上命名standard_id的列sections,但它是命名class_id的,因此您需要手动设置正确的列名。

希望能帮助到你。


推荐阅读