Jasperjon
Jasperjon

Reputation: 447

Create object through relationship

A user has_one avatar and an avatar belongs_to user. How should I create an avatar for a user? I could do this:

user #=> <# a user object >

Avatar.create(name: 'image', user_id: user.id)

But is there a better way? I thought maybe I could do this:

user.avatar.new(name: 'image')

Upvotes: 0

Views: 44

Answers (1)

Mischa
Mischa

Reputation: 43318

You can use build_avatar or create_avatar like this:

user.build_avatar(name: 'image') # Instantiates avatar object
user.create_avatar(name: 'image') # Instantiates and saves to the database

Upvotes: 1

Related Questions