Rails Active Record:has_many错误(NameError:未初始化的常量)

时间:2022-09-29 05:28:34

Edited: solved with

编辑:解决

has_many :imagens, :class_name => 'Imagem', :dependent => :delete_all

The problem I am facing looks a lot like this one: Rails : uninitialized constant error on Active Record destroy

我面临的问题看起来很像这个:Rails:Active Record销毁时未初始化的常量错误

My iflections file has the following:

我的iflections文件包含以下内容:

inflect.plural 'imagem', 'imagens'
inflect.singular 'imagens', 'imagem'

When I try to get the images, it raises and error:

当我试图获取图像时,它会引发错误:

veiculo = Veiculo.first
veiculo.imagens #uninitialized constant Veiculo::Imagen

I don't know why this happens

我不知道为什么会这样

class Veiculo < ActiveRecord::Base
  has_many :caracteristicas, :dependent => :delete_all
  has_many :imagens, :dependent => :delete_all
  # more irrelevant code
end

class Imagem < ActiveRecord::Base
  belongs_to :veiculo
  # more irrelevant code, has attached file
end

1 个解决方案

#1


1  

I had the same problem just now and found the answer: rails' conventions. You need to follow them when creating your models AND when using has_many :through / belongs_to in them.

我刚才遇到了同样的问题并找到了答案:rails的惯例。在创建模型时以及在其中使用has_many:through / belongs_to时,您需要遵循它们。

class Imagem < ActiveRecord::Base
  belongs_to :veiculo
  # more irrelevant code, has attached file
end

It should be:

它应该是:

belongs_to :veiculos

Because "veiculo".pluralize gives us "veiculos" (you can test this in your console!). This should avoid the need of :class_name, which I personally don't like. :)

因为“veiculo”.pluralize给了我们“veiculos”(你可以在你的控制台中测试它!)。这应该避免需要:class_name,我个人不喜欢。 :)

Also, in case you missed it (I did, twice), you need to use singular names in your relationship table, like belongs_to :veiculo and belongs_to :imagem.

此外,如果你错过了它(我做了两次),你需要在你的关系表中使用奇异的名字,比如belongs_to:veiculo和belongs_to:imagem。

#1


1  

I had the same problem just now and found the answer: rails' conventions. You need to follow them when creating your models AND when using has_many :through / belongs_to in them.

我刚才遇到了同样的问题并找到了答案:rails的惯例。在创建模型时以及在其中使用has_many:through / belongs_to时,您需要遵循它们。

class Imagem < ActiveRecord::Base
  belongs_to :veiculo
  # more irrelevant code, has attached file
end

It should be:

它应该是:

belongs_to :veiculos

Because "veiculo".pluralize gives us "veiculos" (you can test this in your console!). This should avoid the need of :class_name, which I personally don't like. :)

因为“veiculo”.pluralize给了我们“veiculos”(你可以在你的控制台中测试它!)。这应该避免需要:class_name,我个人不喜欢。 :)

Also, in case you missed it (I did, twice), you need to use singular names in your relationship table, like belongs_to :veiculo and belongs_to :imagem.

此外,如果你错过了它(我做了两次),你需要在你的关系表中使用奇异的名字,比如belongs_to:veiculo和belongs_to:imagem。