Get will_paginate to determine the user offset on the first page

I am creating a news section on my rails site , and it uses will_paginate to paginate. Now I was wondering how I can specify a custom offset for the first page with will_paginate. something like that:

@featured_news = Post.first @news = Post.offset(1).paginate(:page => params[:page]) 

I need the latest news to be special and not be included in @news objects.

how can i achieve this

thank you for your time!

+6
source share
1 answer

will_paginate redefines all query conditions offset and limit to get the rows of a specific page. I see two options for you:

Ugly: take advantage of the fact that will_paginate works on collections and uses this syntax (it will load your entire table, though)

 @news = Post.offset(1).all.paginate(:page => params[:page]) 

Longer: will_paginate gem so that it can handle custom offsets. I have not tried, but something like this should work (changes to the jewels highlighted)

 # will_paginate / lib / will_paginate / active_record.rb module Pagination def paginate(options) options = options.dup pagenum = options.fetch(:page) { raise ArgumentError, ":page parameter required" } per_page = options.delete(:per_page) || self.per_page total = options.delete(:total_entries) ####################################### custom_offset = options.delete(:offset) ####################################### count_options = options.delete(:count) options.delete(:page) ####################################################### # rel = limit(per_page.to_i).page(pagenum) rel = limit(per_page.to_i).page(pagenum, custom_offset) ####################################################### rel = rel.apply_finder_options(options) if options.any? rel.wp_count_options = count_options if count_options rel.total_entries = total.to_i unless total.blank? rel end ################################ # def page(num) def page(num, custom_offset = 0) ################################ rel = scoped.extending(RelationMethods) pagenum = ::WillPaginate::PageNumber(num.nil? ? 1 : num) per_page = rel.limit_value || self.per_page ################################################################## # rel = rel.offset(pagenum.to_offset(per_page).to_i) rel = rel.offset(pagenum.to_offset(per_page).to_i + custom_offset) ################################################################## rel = rel.limit(per_page) unless rel.limit_value rel.current_page = pagenum rel end end 

This will allow you to use this syntax:

 @news = Post.paginate(:page => params[:page], :offset => 1) 
+9
source

Source: https://habr.com/ru/post/897814/


All Articles