vendredi 26 avril 2019

Rails (Object doesn't support #inspect) / NoMethodError (undefined method `[]' for nil:NilClass)

I have a model "Section". Whenever I try to iterate over Section object, like, "Section.all" or "Section.create", I get error as "(Object doesn't support #inspect)" in rails console and "NoMethodError (undefined method `[]' for nil:NilClass)" in the terminal.

I really need some help since it has become a road blocker.

Ruby : ruby 2.6.1p33

Rails : 5.2.3

Section migration

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

Section model

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

Controller code

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

  render json: @sections
end

Terminal output

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

Rails console Input

Section.all

Rails console output

(Object doesn't support #inspect)

Strangely, when Section table is empty, console output is

#<ActiveRecord::Relation []> 

Thanks in advance.

Aucun commentaire:

Enregistrer un commentaire