views:

229

answers:

3

Another newbie Ruby on Rails question:

In my post view, I want to show the authors name. The post database table stores the authors id which is the same as the users id column in the users table. The user also has a username column in the user table.

So having the users id, how do I get the users name?

+4  A: 
User.find(user_id).username

is one way.

If you were to have a belongs_to relationship between post and user it would be

post.user.username

which is much more 'the Rails way'.

DanSingerman
Wow, that was easier than I expect >.<. This is ok to use in a view?
GreenRails
The second one definitely is. The first one less so.
DanSingerman
Hmm I have "belongs_to :user" in my post model but post.user.login does not work
GreenRails
Got it working! Thanks!
GreenRails
A: 

if you have the id of the author of a post, you should be able to pass that to the find method on your user class. something like this "User.find(post.author_id)" would yield a user object that you could get the username of.

mark
+3  A: 

In your Post model, you should have:

belongs_to :author, :class_name => 'User'

Then from your view, you can access the username with @post.author.username

zgchurch
Thanks. I am getting "You have a nil object when you didn't expect it!The error occurred while evaluating nil.login" though
GreenRails
You may need to add a :foreign_key => 'authors_id' (or whatever your column name is) if it's not predictable by rails.
Swards