Reputation: 11588
I'm currently using:
@user = User.find(params[:id])
@posts = Post.find(:all, :conditions => ["user_id = ?", @user.id])
@comments = Comment.find(:all, :conditions => ["user_id = ?", @user.id])
Which identifies the user, and lists all their comments they've made. However, I want to set a local variable for use in the _comment.html.erb template. I want the variable to list the post's name located in the 'name' column of the post table.
I tried doing:
@post_id = @comments.post_id
@post_name = @post_id.name
But it showed an array error (because @comments lists the array of user comments). I need to find a way to be able to find the post_id for EACH comment. Yet when I try using something like
@post_id = @comments.each.post_id
It shows an error because it doesn't recognise 'post_id' as a method. I want it to output whatever's in the post_id column for EACH comment.
Upvotes: 1
Views: 1088
Reputation: 11
class User
has_many :posts
end
class Post
belonds_to :user
has_many :comments
end
class Comment
belongs_to :post
end
<h1>users contriller</h1>
@user = User.includes(:posts).where(:id => params[:id]).first
<h1>in posts view</h1>
<div class="comments">
<% @user.posts.each do |p| %>
<div class="post">
<%= p.name %>
</div>
<% end %>
</div>
<h1>in comment view</h1>
<div class="comments">
<% @user.posts.each do |p| %>
<div class="post">
<%= p.comments.body %>
</div>
<% end %>
</div>
Upvotes: 1
Reputation: 66
Post has many comments
and comment belongs to post. the should create the foreign key or the glue between post and comment.
remember that @user has all the post with the comment attached.
So to get to the comments id,go from @user.each.post({|post|
post.comment}
Upvotes: 0
Reputation: 141869
Don't issue queries yourself when you can leverage associations better.
If a user has_many
posts, and a post has_many
comments, you can simply do.
user.posts
and
post.comments
Also, it looks like a user has_many
comments, so you can directly do
user.comments
To get the post id from a comment, make a comment belongs_to
a post, then you can do:
comment.post.id # or comment.post.name directly
Upvotes: 1
Reputation: 239270
You're going about this all wrong. The idea is to use associations so rails will provide accessors for you. You should only be using find
to get your top-most record. Rails will populate the associations for you.
def User
has_many :posts
has_many :comments
end
def Post
belongs_to :user
end
Your code then becomes:
@user = User.find(params[:id])
# you can omit these and just use @user.posts and @user.comments in your view
@posts = @user.posts
@comments = @user.comments
If you want to output something for each comment, then use a loop in your view
<div class="comments">
<% @user.posts.each do |p| %>
<div class="post">
<%= p.body %>
</div>
<% end %>
</div>
Upvotes: 5