开发者

Displaying Nested Scaffolds on Index

I'm trying to display something like this on posts/index.html.erb

Post #1
  Comment #1 for Post #1
  Comment #2

Post #2
  Comment #1 for Post #2

etc.

It works fine if I go to /posts/1/comments/, /posts/2/comments/ etc

Since it's using the index file, there is no :post_id in the URL and it throws a nil error. The mode开发者_高级运维ls use the appropriate have_many and belongs_to.

Here's part of routes.rb

resources :posts do
  resources :comments
end

resources :posts

Here's part of my posts_controller.rb

def index
@posts = Post.all
@comments = params[:post_id][:desc]

respond_to do |format|
  format.html # index.html.erb
  format.xml  { render :xml => @posts }
 end
end

Here's part of index.html.erb

<% @posts.each do |post| %>
  <tr>
    <td><%= post.title %></td>
    <td><%= link_to 'Show', post %></td>
    <td><%= link_to 'Edit', edit_post_path(post) %></td>
    <td><%= link_to 'Destroy', post, :confirm => 'Are you sure?', :method => :delete %></td>
  </tr>
<tr><td><%= @comments %></td></tr>
<% end %>
</table>

Thanks!


Well, since comments belongs_to a given post, you just need to have a separate loop in the view to iterate over each of the comments for a given post.

So take the @comments var out of your controller and index view, and do this in the index view instead where you currently have @comments:

<% for comment in post.comments %>
  <tr><td><%= comment.user_name %><%= comment.text %></td></tr>
<% end %>

I made the user_name and text attrs up of course you would use whatever is in your comment model.

ian.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜