Looking for a short term fix for limiting record display number without :limit => 10
I am wondering if there is a way to complete this hack that I am trying to do with my Ruby on Rails app. I'm having trouble with some associations and I can't find the solution. You can see that question here.
In the mean time I am wanting to limit the display of records to a number like 10
but I don't want to do it in the controller through the :limit => 10
manner because I need to loop through all the records. I'm not even sure if this is possible but thought I would ask.
My view code is:
<% @comments.each do |comment| %>
<% if comment.workout.user_id 开发者_开发百科== current_user.id %><br/>
<%= link_to (comment.user.username), comment.user %> <br/>
<%= time_ago_in_words(comment.created_at) %> <br/>
<%= link_to (comment.workout.title), comment.workout %><br/>
<%= sanitize(simple_format(comment.body), :tags => %w(p)) %>
<% end %>
<% end %>
My controller is simply calling
@comments = Comment.all(:order => "created_at DESC")
I would do all that in the controller. Views shouldn't be doing that logic. You say you don't want to only limit to 10, because you want all and do some filter. You can just:
@comments = Comment.all(:joins => :workout, :conditions => {:workouts =>{:user_id => current_user.id}}, :order => "created_at DESC", :limit => 10)
@comments[0..9]
and
@comments[10..-1]
Is the will-paginate gem the droid you're looking for?
After adding the gem to your environment.rb and installing it, you would modify your controller so that it calls paginate rather than find
or all
:
@comments = Comment.paginate(:all, :order => "created_at DESC", :per_page => 10)
And then in your view, add the pagination controls (links to advance a page, go back a page, &c.)
<%= will_paginate @comments %>
精彩评论