Rivisto: ho modificato la risposta per utilizzare before_create e creare, non creare, i modelli associati. Il macchinario ActiveRecord si occupa quindi di salvare i modelli associati una volta salvato il genitore.
Ho anche testato questo codice!
# in your Room model...
has_many :doors
before_create :build_main_door
private
def build_main_door
# Build main door instance. Will use default params. One param (:main) is
# set explicitly. The foreign key to the owning Room model is set
doors.build(:main => true)
true # Always return true in callbacks as the normal 'continue' state
end
####### has_one case:
# in your Room model...
has_one :door
before_create :build_main_door
private
def build_main_door
# Build main door instance. Will use default params. One param (:main) is
# set explicitly. The foreign key to the owning Room model is set
build_door(:main => true)
true # Always return true in callbacks as the normal 'continue' state
end
Aggiunto ...
Il metodo build è aggiunto da macchinari del modello possessore dalla dichiarazione has_many. Poiché l'esempio utilizza has_many: doors (nome modello Door), la chiamata build è doors.build
Vedere docs for has_many e has_one per visualizzare tutti i metodi aggiuntivi che vengono aggiunti.
# If the owning model has
has_many :user_infos # note: use plural form
# then use
user_infos.build(...) # note: use plural form
# If the owning model has
has_one :user_info # note: use singular form
# then use
build_user_info(...) # note: different form of build is added by has_one since
# has_one refers to a single object, not to an
# array-like object (eg user_infos) that can be
# augmented with a build method
Rails 2.x ha introdotto l'opzione di salvataggio automatico per le associazioni. Non penso si applichi a quanto sopra (sto usando il default). Autosave testing results.
fonte
2010-08-17 04:01:36
Il modello figlio nel mio esempio è chiamato "user_info", quando provo a fare 'user_info.create (: main => true)' it errori e dice 'undefined metodo \ 'create 'per nil: NilClass' – Reti
in realtà, il modello è tecnicamente chiamato' userInfo' – Reti
Prova 'UserInfo.create' – zetetic