views:

41

answers:

2

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.

+5  A: 

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>
meagar
And to answer question itself, you can do "comment.post.name" in your template.
Nikita Rybak
You can only do comment.post.name if you've set up the belongs_to and has_many associations. Without that, even though the tables have post_id and user_id columns, they still won't know who or what they belong to unless told.
AboutRuby
I can extract data from the 'user_id' column in the Post table, but I can't figure out how to then use that 'user_id' data to find data from the 'name' column in the User table.The User table has an 'id' and a 'name' column; the 'id' column would be exactly the same as the 'user_id' column in the Post table.
Jamie
@Jamie You're still not thinking about this correctly. You don't have to *find* the username. Just use `@user.post.name` or `@user.comment.name`. Rails handles the rest. I suggest you read a Rails tutorial, because you don't know enough about how models work to be trying to use them.
meagar
+1  A: 

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
Anurag