I Rails if you have a model Walrus that has_many :bubbles
(and Bubble belongs_to :walrus
, you can create a new Bubble that is associated with the Walrus like so:
chuckles = Walrus.create
chuckles.bubbles.create
But what if Walrus has_one :bubble
? chuckles.bubble.create
is a no go (as it is nil
). How can I do the equivalent without just passing in the Walrus in the Bubble.create
?
For has_many
chuckles.bubbles.build
For has_one
chuckles.build_bubble
In your example above, I think you should have been using build. It adds chuckles id to bubble object. Also when chuckles is saved, bubbles will be saved automatically as well
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.