Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Ruby Active Record Associations in Rails Active Record Associations Association Methods

Jason Smith
Jason Smith
17,879 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

4 Answers

Jason Smith
Jason Smith
17,879 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,879 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

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

Thanks guys i was really losing it .