hohner
hohner

Reputation: 11588

How do I access fields from another model through a has_many relationship?

I'm currently using:

@user = User.find(params[:id])
@posts = @user.posts
@comments = @user.comments

To display all my comments with this code in my template:

<% @user.comments.each do |p| %>
  <p>Commented on <%= p.post.user_id %>'s post</p>
  <p><%= p.body %></p>
<% end %>

Each post has a 'user_id' column which is the user's ID for whoever created the post. I can output this 'user_id' data because the Post and the User model has_many :comments, and the Comment model belongs_to both the Post and the User model.

I want to use the 'user_id' data from p.post.user_id to find the user's name from the User database table. The user's name is located in the 'name' column, and the user's ID is located in the 'id' column. How do I use p.post.user_id in the User controller to then find user's with the same ID so I can then output their name?

Upvotes: 0

Views: 200

Answers (1)

Nikita Rybak
Nikita Rybak

Reputation: 68006

If you have belongs_to and has_many in place, you'll have access to the whole User object from Post object:

<%= p.post.user.name %>

Upvotes: 1

Related Questions