1.9.3p194 :023 > u.build_image unless u.image
Image Load (0.4ms) SELECT `images`.* FROM `images` WHERE `images`.`user_id` = 2 LIMIT 1
(0.2ms) BEGIN
(0.2ms) COMMIT
=> #<Image id: nil, desc: nil, user_id: 2, created_at: nil, updated_at: nil>
1.9.3p194 :024 > u.image
=> #<Image id: nil, desc: nil, user_id: 2, created_at: nil, updated_at: nil>
— Копипаста из
api.rubyonrails.org/classes/ActiveRecord/Associations/ClassMethods.html
One-to-one associations
Assigning an object to a has_one association automatically saves that object and the object being replaced (if there is one), in order to update their foreign keys — except if the parent object is unsaved (new_record? == true).
If either of these saves fail (due to one of the objects being invalid), an ActiveRecord::RecordNotSaved exception is raised and the assignment is cancelled.
If you wish to assign an object to a has_one association without saving it, use the build_association method (documented below). The object being replaced will still be saved to update its foreign key.