bimbom22
bimbom22

Reputation: 4510

How to clean up my view

I'm trying to do a blog post's comments section where comments are listed below the post.

I have Posts and PostComments classes

I have posts/show.html.erb to show the blog post and I have made a post_comments/_post_comment.html.erb partial to render a comment

in posts/show.html.erb i have the following:

<% @post.post_comments.each do |comment| %> 
    <%= render :partial => '/post_comments/post_comment', :locals=>{ :comment => comment } %>
<% end %>

Is there any way to move that loop out of the view and into a method in the controller? I want to call will_paginate on it, and I don't think I can do that if the logic is in the view like it is now.

Upvotes: 0

Views: 154

Answers (2)

Harish Shetty
Harish Shetty

Reputation: 64363

Try the render partial collection :

<%= render :partial    => '/post_comments/post_comment', 
           :collection => @post_comments  %>

This will render /post_comments/_post_comment.erb and pass the local variable post_comment to the template for display. An iteration counter will automatically be made available to the template with a name of the form post_comment_counter.

If you have the page, page size parameters available then you can call paginate directly in the view.

<%= render :partial    => '/post_comments/post_comment', 
           :collection => @post.post_comments.paginate(:page => params[:page]) %>

Upvotes: 0

shingara
shingara

Reputation: 46914

If you want call will_paginate on it do

<% @post.post_comments.paginate(params[:page], params[:per_page]).each do |comment| %> 
    <%= render :partial => '/post_comments/post_comment', :locals=>{ :comment => comment } %>
<% end %>

And it's better to define in your controller are instance attribute to this return

@post_comments = @post.post_comments.paginate(params[:page], params[:per_page])

And in you view

<% @post_comments.each do |comment| %> 
    <%= render :partial => '/post_comments/post_comment', :locals=>{ :comment => comment } %>
<% end %>
<%= will_paginate(@post_comments) %>

In this case, this loop is only to record really view. Not all records.

Upvotes: 2

Related Questions