【问题标题】:Bizarre error in pry when testing associations测试关联时的奇怪错误
【发布时间】:2016-07-31 14:58:53
【问题描述】:

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

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

然后在 pry session 中我只是这样做:

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 子目录链。我在那里替换了它以保持输出的可读性。

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

【问题讨论】:

  • 将类名从 Grave 更改为 Gravesite 解决了这个问题。我不知道系统中的什么 gem 干扰了 Grave 类名,但无论它是一个巨大的、嘈杂的 WTF。

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


【解决方案1】:

这是 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"

【讨论】:

  • 哇,我以为我只需要在“我永远不会知道”下永久归档这个。它不会让我再奖励 18 个小时的赏金,但你会得到它。非常感谢。
  • 是的,线索在错误消息“NameError:未初始化的常量 Lot::Grafe”中
  • 所以我找到了一个随机网站,展示了古英语动词“grafan”的各种结合方式,意思是to dig, dig up; to grave; engrave, chisel, carve。其中一个变位确实是“grafe”。
  • 是的,不是说它错了,只是你可以用你期望/希望它的内容覆盖它......英语有时是一种奇怪的语言,因为它可能是这么多语言的混合体由于当时谁占领了英格兰,哈哈
  • 是的,这更像是一个有趣的事实——让我想知道他们在哪里提出了多元化/单一化的“规则”。无论如何我都会投票赞成说这是错误的:)
猜你喜欢
  • 1970-01-01
  • 2018-09-22
  • 1970-01-01
  • 2017-03-09
  • 2011-12-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-01-21
相关资源
最近更新 更多