0

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?

Chris
  • 11,819
  • 19
  • 91
  • 145

1 Answers1

4

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

sohaibbbhatti
  • 2,672
  • 22
  • 21