Đã sửa đổi: Tôi đã sửa đổi câu trả lời để sử dụng before_create và building, chứ không phải tạo, các mô hình được liên kết. Máy móc ActiveRecord sau đó sẽ chăm sóc lưu các mô hình liên quan sau khi cha mẹ được lưu.
Tôi thậm chí đã thử nghiệm mã này!
# 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
Added ...
Phương pháp xây dựng được bổ sung bằng cách máy móc mô hình sở hữu bằng cách tuyên bố has_many. Vì ví dụ sử dụng has_many: cửa (tên cửa kiểu), cuộc gọi xây dựng là doors.build
Xem docs for has_many và has_one để xem tất cả các phương thức bổ sung được thêm vào.
# 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
Đường ray 2.x giới thiệu tùy chọn tự động lưu liên kết. Tôi không nghĩ rằng nó áp dụng cho các bên trên (tôi đang sử dụng mặc định). Autosave testing results.
Nguồn
2010-08-17 04:01:36
Mô hình con trong ví dụ của tôi được gọi là "user_info", khi tôi cố gắng thực hiện 'user_info.create (: main => true)' lỗi và nói 'undefined phương thức \ 'create 'cho nil: NilClass' – Reti
thực sự, mô hình được gọi là' userInfo' – Reti
Thử 'UserInfo.create' – zetetic