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
Craig Booker
14,968 PointsAssociating Objects With User Model
I have gone through all but the push notifications tutorial on the Rails path. I am wanting to add objects to the user model. I am trying to add vehicles to a user. So, a user can have one vehicle or multiple vehicles. There can also be more than one user per household. Just say we start the vehicle object with have a year, model, and make. How would we go about that?
1 Answer
Brandon Barrette
20,485 PointsCreate a model for the vehicle (use model to create model or scaffold to get a RESTful controller, index, show, etc)
rails g scaffold vehicle user:references vehicle:string model:string year:integer
The "references" automatically adds a reference to the user and adds an index in your database. Then in your user model, you can do:
has_many :vehicles
Your vehicle model should already say
belongs_to :user
Now with that, you can call
user.vehicles
And it will tell you the vehicles that belong to a user. Since it is a has_many relation, there can be more than one. Hope that helps!
Craig Booker
14,968 PointsCraig Booker
14,968 PointsThis worked great! Thank you! Doing this is really helping me understand how rails works. I was making it more difficult than it actually is. Again thank you!
Craig Booker
14,968 PointsCraig Booker
14,968 PointsOkay, so the profile model is really not fully developed as is, according to what I followed in the tutorial. For example, it has the route:
profile GET /:id(.:format) profiles#showBut it doesn't have new, edit, delete. So, how would I fill this profiles model out without destroying what is in place?
Brandon Barrette
20,485 PointsBrandon Barrette
20,485 PointsYou don't really want a new, edit, delete for the profile, since the profile itself isn't a model, it's a place where a bunch of other data (from user model, status model, etc) is displayed about a user. So if you wanted to show the vehicles of a user, you would need to add that to the profile controller.
I suggest looking at how we displayed statuses on the profile, then mimic that to get your vehicles to show up. Then, if you have other models that relate to a user, do the same.