2008年9月1日 星期一

will_paginate使用心得

延續之前的文章
http://hdj-berkeley.blogspot.com/2008/08/scaffold.html
如果我們要將大量資料分類成好幾個分頁
就可以用現在的套件will_paginate

首先在model裡增加search的條件

# models/product.rb
def self.search(search, page)
paginate :per_page => 5, :page => page,
:conditions => ['title like ?', "%#{search}%"],
:order => 'title'
end

這裡的title是依照你想要的排序自己選取的
也可以改為id

接著增加controller的條件
將變數傳回給viewer

# products_controller.rb
def index
@products = Product.search(params[:search], params[:page])
end


最後修改products/index.rhtml
讓分頁呈現在網頁上
<%= will_paginate @products %>


這樣就大功告成啦

主要參考:
http://railscasts.com/episodes/51

其它參考網址:
http://iceskysl.1sters.com/?action=show&id=307&page=1
http://iceskysl.1sters.com/?action=show&id=42&page=1
http://www.ruby-lang.org.cn/forums/thread-985-1-1.html
http://www.j-kanban.com/bbs/thread-3690-1-1.html
Related Posts Plugin for WordPress, Blogger...