Search code examples
ruby-on-railsrails-activerecordmodel-associationsruby-on-rails-4.2

Bizarre error in pry when testing associations


So I'm seeing this strange error when I try to do a fairly simple interactive test of an associations I've added. Here are the two models:

class Lot < ActiveRecord::Base
  has_many :graves
  belongs_to :block
end

class Grave < ActiveRecord::Base
  belongs_to :lot
end

Here are the table creation migrations:

class CreateGraves < ActiveRecord::Migration
  def change
    create_table :graves do |t|
      t.integer :grave_number
      t.integer :lot_id

      t.timestamps null: false
    end
  end
end

class CreateLots < ActiveRecord::Migration
  def change
    create_table :lots do |t|
      t.integer :lot_number
      t.integer :map_type

      t.timestamps null: false
    end
  end
end

I'm invoking pry with:

pry -r ./config/environment.rb

Then in the pry session I simply do:

lot = Lot.new
l.graves

and I get this error:

NameError: uninitialized constant Lot::Grafe
from /.../activerecord-4.2.6/lib/active_record/inheritance.rb:158:in `compute_type'

The ... there is simply the path to my rbenv installation and the ruby 2.3.0 subdirectory chain. I replaced it in there to keep that output readable.

I've got several other similar associations defined on other classes and all of those work as expected.


Solution

  • This is an issue with Rails' inflectors. It happens at weird times and is a strange Rails quirk.

    2.3.1 :004 > a = "Grave"
     => "Grave"
    2.3.1 :005 > a.pluralize
     => "Graves"
    2.3.1 :006 > a = "graves"
     => "graves"
    2.3.1 :007 > a.singularize
     => "grafe"
    

    You can override the default behavior in the often overlooked ./config/inflections.rb file :)

    ActiveSupport::Inflector.inflections(:en) do |inflect|
      inflect.irregular 'grave', 'graves'
    end
    

    after change

    2.3.1 :001 > a = "grave"
     => "grave"
    2.3.1 :002 > a.pluralize
     => "graves"
    2.3.1 :003 > a = "graves"
     => "graves"
    2.3.1 :004 > a.singularize
     => "grave"