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
Matin Amirshahi
5,602 PointsTrouble with belongs_to association
Hi guys, I've been dealing with a frustrating issue regarding 'belongs_to' association in rails. Briefly, I want to establish a connection between User and Status models as in the Treebook example. My statuses table has a "user_id" column setup properly and the "belongs_to :user" code is put in my Status model already which should be enough but for instance,when trying to use <% @status.user.id %>, I'd get no method error! Any help/suggestion would much be appreciated!
2 Answers
Brandon Barrette
20,485 PointsThe association has to be double sided. Meaning in your user model, there needs to be
#user.rb
has_many: statuses
Once that is established, rails will be able to call:
@status.user
#output = #<User id: 7, first_name: "Test", last_name: "User", profile_name: "TestUser", email: "test@teamtreehouse.com"... etc
What's happening here is rails is looking for the user, not just pulling the user_id from your status table. Rails takes the user_id, then looks that id up in the users table to return the actual user to you, not just the id. If all you want is the id, then you should call:
@status.user_id
#output = 7
Matin Amirshahi
5,602 PointsThank you! I'll try and see if this works!