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.
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
findto get your top-most record. Rails will populate the associations for you.Your code then becomes:
If you want to output something for each comment, then use a loop in your view