ruby-on-rails - 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 []>
解决方案
除了@Tom Lord 的评论,您还必须更正关联:
class Section < ApplicationRecord
belongs_to :class, class_name: "Standard"
belongs_to :class_teacher, class_name: "User"
end
由于您的迁移为引用创建了一个class_id
和class_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
的,因此您需要手动设置正确的列名。
希望能帮助到你。
推荐阅读
- reactjs - i18n 在路径中加载 en-US
- git - Vscode 主机验证密钥失败。缩放器
- rust - 允许使用用户定义的类型创建特征对象?
- typescript - 有没有办法在我的 webview 中自动使用启用的扩展
- ios - 在 swift iOS 中自动从设备中检索应用推送令牌
- android - 通知栏和工具栏之间的空间
- php - 无法在数据库中第二次添加数据,但第一次成功 Laravel
- html - CKEditor:如何将按钮控件“放在后面”
- mysql - 如何使用 Spring Data JPA 从表中获取数据并将该数据设置在其他表中?
- laravel - 如何在程序中使用 Laravel 7 中的错误?