Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

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 .