[英]NameError, uninitialized constant
我正在嘗試使用Rails提交一個簡單的表單。
class BibliographiesController < ApplicationController
def creer #this has been localized for create
@bibliography = Bibliography.new(bibliographie_params)
@bibliography.save
redirect_to @bibliography
end
#etc etc
private
def bibliographie_params
params.require(:bibliographie).permit(:titre, :soustitre, :auteur_un, :auteur_deux, :auteur_trois, :auteur_quatre, :genre, :recueil, :review, :revue_numero, :annee, :revue_page, :editeur, :lieu, :commentaire)
end
end
遷移文件包含相同的字段。 titre和soustitre都是字符串,而auteur_un是整數。
提交表單時,出現錯誤,即:
NameError in BibliographiesController#creer
uninitialized constant Bibliography::AuteurUn
params_hash包含:
"bibliographie"=>{
"titre"=>"La vie urbaine à Douai au Moyen-Âge",
"soustitre"=>"rien",
"auteur_un"=>"1",
"genre"=>"source",
"recueil"=>"aucun",
"review"=>"",
"revue_numero"=>"",
"annee"=>"",
"revue_page"=>"",
"editeur"=>"",
"lieu"=>"",
"commentaire"=>""}
這是我的書目課程:
class Bibliography < ApplicationRecord
has_one :auteur_un, foreign_key: "auteurs_id"
has_one :auteur_deux, foreign_key: "auteurs_id"
has_one :auteur_trois, foreign_key: "auteurs_id"
has_one :aauteur_quatre, foreign_key: "auteurs_id"
has_one :review, foreign_key: "reviews_id"
end
似乎Rails期望auteur_un是一個類或常量。 但是我不明白為什么。
謝謝
通常,當您想使用一個不同於some_model_id
的屬性來關聯一個外部模型(例如: some_model
,應該與has_one
關聯一起使用foreign_key
選項。
您使用auteurs_id
有四個不同的has_one
關聯。
在我看來,您有一個Auteur
模型,並且您希望Bibliography
模型有四個關聯:auteur_un
, :auteur_deux
, :auteur_trois
, :auteur_quatre
,每個都指向一個不同的Auteur
實例。
如果確實如此,我認為您想使用belongs_to
關聯,而不是:
class Bibliography < ApplicationRecord
belongs_to :auteur_un, class_name: "Auteur"
belongs_to :auteur_deux, class_name: "Auteur"
belongs_to :auteur_trois, class_name: "Auteur"
belongs_to :auteur_quatre, class_name: "Auteur"
...
end
該關聯將期望Bibliography
模型具有auteur_un_id
, auteur_deux_id
, auteur_trois_id
和auteur_quatre_id
,因此您將需要修改“ auteur”列(將每個列附加“ _id”)。 例如,您的私有params方法將更改為:
def bibliographie_params
params.require(:bibliographie).permit(:titre, :soustitre, :auteur_un_id, :auteur_deux_id, :auteur_trois_id, :auteur_quatre_id, :genre, :recueil, :review, :revue_numero, :annee, :revue_page, :editeur, :lieu, :commentaire)
end
或者,您可以使用foreign_key
選項,而無需更改列名稱:
class Bibliography < ApplicationRecord
belongs_to :auteur_un, class_name: "Auteur", foreign_key: "auteur_un"
belongs_to :auteur_deux, class_name: "Auteur", foreign_key: "auteur_deux"
belongs_to :auteur_trois, class_name: "Auteur", foreign_key: "auteur_trois"
belongs_to :auteur_quatre, class_name: "Auteur", foreign_key: "auteur_quatre"
...
end
但是,最好遵循Rail的約定。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.