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>开发者_JAVA技巧;
<% 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?
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 %>
精彩评论