Rendering 'belongs_to" in index view question - Ruby on Rails

Posted by bgadoci on Stack Overflow See other posts from Stack Overflow or by bgadoci
Published on 2010-04-12T15:49:42Z Indexed on 2010/04/12 15:53 UTC
Read the original article Hit count: 337

I have created a simple blog application with Ruby on Rails. The applications consists of two tables, posts and comments. Comments belongs_to :post and posts has_many :comments.

I created posts table with the following columns: title:string, body:text. I created the comments table with the following columns: body:text post_id:integer name:string email:string

In the /views/comments/index.html.erb display I would like to show a listing of all comments w/ the post title as well. Currently, the index view only displays post_id, body, name, email.

How do I replace the post_id column with the corresponding post title? Here is my code:

CommentsController Index action:

  def index
    @comments = Comment.all :order => "created_at DESC"
    respond_to do |format|
      format.html # index.html.erb
      format.xml  { render :xml => @comments }
      format.json { render :json => @comments }
      format.atom
    end
  end

/views/comments/index.html.erb

<h1>Listing comments</h1>

<table>
  <tr>
    <th>Post</th>
    <th>Body</th>
  </tr>

<% @comments.each do |comment| %>
  <tr>
    <td><%=h comment.post_id %></td>
    <td><%=h comment.body %></td>
    <td><%=h comment.name %></td>
    <td><%=h comment.email %></td>
  </tr>
<% end %>
</table>

<br />

© Stack Overflow or respective owner

Related posts about ruby-on-rails

Related posts about ruby