2013-05-08 34 views
2

我可以很容易地分页,但我使用两个模型,使它复杂一点。未定义的方法`total_pages'为#<Array:0x8e052a0>,如何正确分页?

首先,这里的控制器

class BrowseController < ApplicationController 

def index 
    @hashtags = Hashtag.find(:all, :order => 'created_at DESC') 
    @posts = post.all 
end 
end 

那么这里的视图(浏览\ index.html.erb)

<ul> 
<% @posts.each do |post| %> 
<% if post.hashtags.present? %> 
<li> <%= link_to post.hashtags.map{|h| "##{h.hashtags}"}.join(', '), post.user %> </li> 
<% else %> 

<% end %> 
<% end %> 
</ul> 

我想分页这一观点。这不仅仅是发布,而是帖子的标签。什么是正确的<%= will_paginate %>代码?

我正在尝试分页帖子的标签,而不仅仅是帖子本身。

+1

不能分页数组,唐不要在@posts上调用'.all',否则你将所有的帖子加载到内存中,这种排序方式与使用分页的全部原因相关 – 2013-05-08 08:58:55

+0

我应该说明你*可以分页数组,但这不是默认行为,我用'paginate_array'方法使用kaminari但will_paginate工作方式不同:http://stackoverflow.com/questions/13187076/paginating-an-array-in-ruby-with-will-paginate – 2013-05-08 08:59:45

回答

4

如果您使用的是真棒will_paginate gem是:https://github.com/mislav/will_paginate,简单的改变控制器代码:

# per_page 30 posts, change :per_page to the number you´d like 
@posts = Post.paginate(:page => params[:page], :per_page => 30) 

,改变你的观点来:

<%= will_paginate @posts %> 
+0

但是,我不分页只是帖子。这是帖子的标签。我还能使用你的代码吗? – rts213 2013-05-08 18:58:54

+0

这不回答这个问题。 – 0112 2014-10-16 19:28:55

相关问题