संशोधित: मैंने संबंधित मॉडल बनाने से पहले, निर्माण और निर्माण, निर्माण, उपयोग करने के लिए उत्तर संशोधित किया। एक बार माता-पिता को सहेजने के बाद ActiveRecord मशीनरी संबंधित मॉडल को सहेजने का ख्याल रखती है।
मैं भी इस कोड का परीक्षण!
# 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
जोड़ा गया ...
निर्माण विधि has_many बयान से, स्वामित्व वाली मॉडल की मशीनरी द्वारा जोड़ा जाता है। चूंकि उदाहरण है has_many: दरवाजे (मॉडल नाम द्वार), बिल्ड कॉल दरवाजे हैं। बिल्ड
docs for has_many और has_one को जोड़े गए सभी अतिरिक्त तरीकों को देखने के लिए देखें।
# 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
रेल 2.x ने एसोसिएशन के लिए ऑटोओव विकल्प पेश किया। मुझे नहीं लगता कि यह उपरोक्त पर लागू होता है (मैं डिफ़ॉल्ट रूप से उपयोग कर रहा हूं)। Autosave testing results.
स्रोत
2010-08-17 04:01:36
मेरे उदाहरण में बाल मॉडल को "user_info" कहा जाता है, जब मैं 'user_info.create (: main => true) 'त्रुटियों को करने का प्रयास करता हूं और कहता है' अपरिभाषित विधि के लिए \ 'create' विधि: NilClass' – Reti
वास्तव में, मॉडल को तकनीकी रूप से 'userInfo' – Reti
कहा जाता है' UserInfo.create' – zetetic