rails中weill_paginate的paginate方法中不能使用额外参数的解决办法
生活随笔
收集整理的這篇文章主要介紹了
rails中weill_paginate的paginate方法中不能使用额外参数的解决办法
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
? ? 我們知道高版本中的rails中的分頁功能已經放在will_paginate這個gem中,我們在控制器方法中往往需要調用其paginate方法來實現分頁數據集控制,舉個例子:正常的情況我們想要每頁顯示10條記錄可以這么寫:
Item.paginate(page:params[:page],per_page:10)
但是我們又想要降序排列記錄呢?書上給出的例子如下:
Item.paginate(page:params[:page],per_page:10,order:'created_at DESC')
可惜該方法在新的rails中已不能使用!通過查看will_paginate的源代碼可以看到,原因是如果paginate的調用包含其他參數的話,會調用Active_Record::Relation中的實例方法apply_finder_options:
module Paginationdef paginate(options)options = options.duppagenum = options.fetch(:page) { raise ArgumentError, ":page parameter required" }per_page = options.delete(:per_page) || self.per_pagetotal = options.delete(:total_entries)count_options = options.delete(:count)options.delete(:page)rel = limit(per_page.to_i).page(pagenum)puts "#{'*'*100}:#{rel}\#"rel = rel.apply_finder_options(options) if options.any?rel.wp_count_options = count_options if count_optionsrel.total_entries = total.to_i unless total.blank?relend end
可是該方法在新rails中不存在了。解決辦法是在控制器調用paginate前排序即可:
@orders = Order.order('created_at DESC').paginate(page:params[:page],per_page:10)
總結
以上是生活随笔為你收集整理的rails中weill_paginate的paginate方法中不能使用额外参数的解决办法的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: ASP.NET MVC Music St
- 下一篇: 顺丰快递,果然不一般!