irl_irl
irl_irl

Reputation: 3975

Ruby on Rails: Access information from other models?

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?

Upvotes: 4

Views: 7564

Answers (3)

zgchurch
zgchurch

Reputation: 2322

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

Upvotes: 3

mark
mark

Reputation: 126

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.

Upvotes: 0

DanSingerman
DanSingerman

Reputation: 36532

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'.

Upvotes: 10

Related Questions