Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 699
irl_irl Avatar asked Dec 14 '22 02:12

irl_irl


1 Answers

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

like image 106
DanSingerman Avatar answered Dec 26 '22 00:12

DanSingerman