2011-12-27 56 views
1

編輯:解決了Rails的活動記錄:的has_many錯誤(NameError:未初始化的常數)

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

我現在面臨的問題 長得像這樣的:Rails : uninitialized constant error on Active Record destroy

我iflections文件有以下幾種:

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

當我嘗試獲取im年齡,它提出和錯誤:

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

我不知道爲什麼會這樣

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

剛纔我同樣的問題,找到了答案:Rails的約定。創建模型時以及在其中使用has_many:through/belongs_to時,您需要遵循它們。

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

它應該是:

belongs_to :veiculos 

因爲 「veiculo」 .pluralize爲我們提供了 「veiculos」(您可以在控制檯測試此!)。這應該避免需要:class_name,我個人不喜歡。 :)

此外,如果您錯過了它(我做了兩次),您需要在關係表中使用單數名稱,例如belongs_to:veiculo和belongs_to:imagem。

相關問題