开发者

Rails 3 display will_paginate pages from a different view

开发者 https://www.devze.com 2023-02-25 15:05 出处:网络
I\'m using Rails 3 and will_paginate. I have will_paginate successfully working in a triple nested resource. I\'m having trouble linking to the paginate view (page 1 2 3 4) from a different controller

I'm using Rails 3 and will_paginate. I have will_paginate successfully working in a triple nested resource. I'm having trouble linking to the paginate view (page 1 2 3 4) from a different controller. I'm in one controller, but my pagination happens in the nested controller. Say I have a contr开发者_如何转开发ollers 'section' 'topics' and 'replies'. In my show 'topics' controller I do the pagination for all of the replies (because it pulls replies based on the path of the topic). So now I'm in the show section view trying to link to the different pages of the topic (about 7 replies per page). Since I'm in the section controller, I can't easily paginate the replies of a topic, because it is dependent on a loop of topics in the view. Furthermore, I don't necessarily want the 'previous' and 'next' links next to the topic name... I just need (1 2 3 ... 10) or something similar. Is there a way to save this pagination for use in a different controller?

What is the easiest way to do this?

In case you're having a hard time understanding, the view is like a typical forum post that links to different pages:

Section
    Topic A (1 2 3)
    Topic B (1)
    Topic C (1 2 3 ...5)
    Topic D (1 2 3 ...10)

But I'm not sure how to use the will_paginate from a controller that knows nothing about the pagination.


Sorry for answering my own question. It took awhile to figure this out.

I figured it out without using the will_paginate display method. I made my own helper. I don't know if this is the 'correct' way to do things, but it works. I made a helper to output page numbers next to the topics. In my view, I had a group like:

<% @topics.each do |topic| %>
    <%= pageLinks(topic, @section) %>
<% end %>

So then in the helper, I made it like this:

def pageLinks(t, s)
   html = ""
   if t.replies.count > 7
      pageList = []
      1.upto(t.replies.count/6) {|n| pageList << "#{link_to n, section_topic_path(s, t, :page =>n) } "}      
      html << "| page (#{pageList})"
      html.html_safe
   else
      return
   end
end

Basically I divide by the amount of results per page I want and link based on that.

An interesting thing about this code that took me awhile was the link_to :page => n that displays the path /section/id/topic/id?page=n... You have to pass it in a parameter of the path if you're using the path listed in 'rake routes'. I also had a hard time returning the actual html rather than than printing the html itself.

0

精彩评论

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

关注公众号