开发者

Rails pagination of subset of a class

开发者 https://www.devze.com 2023-03-09 16:22 出处:网络
I have a rails app and I\'m 开发者_开发知识库trying to set up pagination for a view of the Essays class. I\'m new to rails... so I can do this for ALL of them, but I only want certain ones to be in th

I have a rails app and I'm 开发者_开发知识库trying to set up pagination for a view of the Essays class. I'm new to rails... so I can do this for ALL of them, but I only want certain ones to be in this list (where all the essays are contained in Essay.find(Ranking.where(:user_id=>current_user.id).essay_id)).

home.html.erb contains (among other things):

`<%= will_paginate @essays%>

<ul class="users">
  <%= render @essays %>
</ul>

<%= will_paginate @essays%>`

in the Pages Controller:

def home
     #...
      @essays = Essay.paginate(:page => params[:page])
end

I tried adding @essays=Essay.find(Ranking.where(:user_id=>current_user.id).essay_id) before the @essays=Essay.paginate(:page => params[:page]) but the method essay_id for the Ranking class is not available here. How do I get around this? Thanks!


This should work:

Essay.joins(:rankings)
  .where(:rankings => {:user_id => current_user.id})
  .paginate(:page => params[:page])


While this can be done with will_paginate. I've had some issues with this plugin for Rails 3. A much smoother solution, in my opinion, was to use another pagination plugin called Kaminari.

Assuming, essay_id is passed as a param, you could try:

@ranking = Ranking.where(:user_id => current_user.id, :essay_id => params[:essay_id]).page(params[:page]).per(10)

Or depending on your logic. If the essay object has already been identified in your controller:

@essay = Essay.find(1234)
@ranking = Ranking.where(:user_id => current_user.id, :essay_id => @essay.id).page(params[:page]).per(10)

And then, in your view:

<%= paginate @ranking %>

Even better, to get you started on Kaminari, you can view this rails cast. As noted from the rails cast:

The first-choice gem for pagination in Rails is will_paginate, but the currently released version doesn’t support Rails 3. There is a pre-release version available that works but it hasn’t been updated for several months. If will_paginate is no longer in active development are there any other gems we could use?

One alternative is Kaminari. This seems to provide a cleaner implementation of pagination and offers several improved features, too, so let’s try it in our application instead.

Hope that helps!


Simply chain paginate method after find method:

@essays=Essay.find(Ranking.where(:user_id=>current_user.id).essay_id).paginate(:page => params[:page])
0

精彩评论

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