测试关联时撬的奇怪错误

时间:2016-07-31 14:58:53

标签: ruby-on-rails rails-activerecord model-associations ruby-on-rails-4.2

当我尝试对我已添加的关联进行相当简单的交互式测试时,我看到了这个奇怪的错误。以下是两种模式:

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

class Grave < ActiveRecord::Base
  belongs_to :lot
end

以下是表创建迁移:

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

我用以下方式调用pry:

pry -r ./config/environment.rb

然后在撬开会话中,我只是这样做:

lot = Lot.new
l.graves

我收到此错误:

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

...只有我的rbenv安装路径和ruby 2.3.0子目录链。我在那里替换它以保持输出可读。

我已经在其他类上定义了其他几个类似的关联,并且所有这些关联都按预期工作。

1 个答案:

答案 0 :(得分:3)

这是Rails的变形金刚的一个问题。它发生在奇怪的时候,是一个奇怪的Rails怪癖。

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"

您可以覆盖经常被忽视的./config/inflections.rb文件中的默认行为:)

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

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"
相关问题