Chris
Chris

Reputation: 12181

Activerecord relation creation via has_one

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?

Upvotes: 0

Views: 151

Answers (1)

sohaibbbhatti
sohaibbbhatti

Reputation: 2682

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

Upvotes: 4

Related Questions