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

Brad Givens
Brad Givens
6,621 Points

Active record association - Pet name & owner

After reviewing the video a couple of times, I still can't seem to create a new name for Pet after calling the Owner.first part

playground.rb
pet = Owner.first

name = pet.name.build

pet.name = "stan"

1 Answer

Hi Brad,

You're pretty close.

It's important to get in the habit of clearly naming your variables sooner rather than later. It will help you think about the problem in the correct way too. Variables are like notes to yourself and to future developers who read your code. Your pet variable is actually the first Owner that you loaded, so you might call that first_owner. Likewise, your name variable is actually the first pet you created for the first Owner, so you might call that first_pet (i'll bet you can come up with better names than what I'm suggesting).

Other than forgetting to save your first Owner's companion to the database you had a little syntax mixup in the second line of your code. You're building(.build) a new pet(.pets) on the first_owner variable and you're saving all of that as a variable called first_pet. first_owner is obviously the variable that you created to load the first Owner, but "pets" in .pets is a way of telling Rails that you want to create a relationship between the first Owner and first_pet. I'm having a tough time explaining how this relationship works, so I am going to leave it for someone else with more experience to try. I also think your lessons will cover this more in depth later on.

#First you load the first Owner.
first_owner = Owner.first

#Next you build her a companion.
first_pet = first_owner.pets.build

#Then you name it, just like you did.
pet.name = "stan"

#And finally, don't forget to save it to the database. 
pet.save