Ruby Active Record Associations in Rails Active Record Associations Association Methods

Jason Smith
Jason Smith
17,878 Points

Any help with this code challenge would be great. I can't seem to figure this out.

We've loaded a Rails environment that includes a Pet model class and an Owner model class which has_many :pets. Code that you type here in playground.rb will work just like the code we've been demonstrating in the Rails console.

Load the first Owner from the database. Then, create a new Pet belonging to that Owner. Set the Pet's name attribute to any string you want, and ensure the Pet is saved to the database.

playground.rb
owner = Pet.first
pet.name = "Jay"
pet.save

3 Answers

Jason Smith
Jason Smith
17,878 Points

I figured it out!

owner = Owner.first owner.pets.create(name: "Jay") owner.save

Jeff Lange
Jeff Lange
8,788 Points

Hey Jason! Because you called create, you don't have to call save afterwards as the create function does this automatically. However, if you just build a Pet object with Pet.new, you'd eventually have to save it.

pet = Pet.new
pet.name = "Max"
pet.owner = Owner.find(1)
pet.save
=> true
Jeff Lange
Jeff Lange
8,788 Points

Since you called create you still don't have to call save on owner. ;)

Jason Smith
Jason Smith
17,878 Points

Thak you Jeff Lange! I am starting to understand it more and more. I wanted to put your answer as best answer but I can't seem to click on your answer or even reply to it.

Thanks again

Mariana Lungu
PRO
Mariana Lungu
Pro Student 7,013 Points

owner = Owner.first pet = owner.pets.create(name: "Coco")