How to Pass a Filter Param to a Read More Link_to Pagination, Rails
Kaminari
A Scope & Engine based, clean, powerful, customizable and sophisticated paginator for modern web app frameworks and ORMs
Features
Clean
Does not globally pollute Assortment
, Hash
, Object
or AR::Base
.
Like shooting fish in a barrel to Use
But parcel the gem, then your models are set up to exist paginated. No configuration required. Don't have to define anything in your models or helpers.
Simple Telescopic-based API
Everything is method chainable with less "Hasheritis". You know, that'due south the modern Rails way. No special collection class or anything for the paginated values, instead using a full general AR::Relation
instance. So, of course you can chain whatever other atmospheric condition before or after the paginator scope.
Customizable Engine-based I18n-aware Helpers
Equally the whole pagination helper is basically just a collection of links and non-links, Kaminari renders each of them through its own fractional template within the Engine. Then, you can easily change their behaviour, style or whatsoever by overriding partial templates.
ORM & Template Engine Agnostic
Kaminari supports multiple ORMs (ActiveRecord, DataMapper, Mongoid, MongoMapper) multiple web frameworks (Rails, Sinatra, Grape), and multiple template engines (ERB, Haml, Slim).
Modern
The pagination helper outputs the HTML5 <nav>
tag past default. Plus, the helper supports Rails unobtrusive Ajax.
Supported Versions
-
Ruby 2.1, ii.2, 2.3, 2.iv, ii.five, two.6, 2.vii, 3.0, 3.ane, three.2
-
Rails 4.ane, four.2, 5.0, 5.1, five.2, 6.0, vi.1, 7.0, 7.i
-
Sinatra ane.4, two.0
-
Haml 3+
-
Mongoid 3+
-
MongoMapper 0.9+
-
DataMapper 1.one.0+
Installation
To install kaminari on the default Track stack, just put this line in your Gemfile:
Then bundle:
If yous're building not-Track of not-ActiveRecord app and want the pagination feature on information technology, please take a expect at Other Framework/Library Support department.
Query Nuts
The page
Telescopic
To fetch the 7th page of users (default per_page
is 25)
Note: pagination starts at page 1, not at page 0 (page(0) volition return the same results every bit page(1)).
Kaminari does not add an order
to queries. To avoid surprises, you should mostly include an order in paginated queries. For case:
User . order ( :name ) . folio ( 7 )
You tin become page numbers or page weather by using below methods.
User . count #=> thousand User . page ( 1 ) . limit_value #=> twenty User . folio ( one ) . total_pages #=> l User . folio ( 1 ) . current_page #=> 1 User . page ( 1 ) . next_page #=> ii User . page ( 2 ) . prev_page #=> ane User . page ( i ) . first_page? #=> true User . page ( 50 ) . last_page? #=> truthful User . page ( 100 ) . out_of_range? #=> true
The per
Telescopic
To show a lot more than users per each page (change the per
value)
User . guild ( :proper noun ) . page ( 7 ) . per ( fifty )
Notation that the per
scope is non directly defined on the models just is just a method divers on the page scope. This is absolutely reasonable considering you will never actually use per
without specifying the page
number.
Continue in mind that per
internally utilizes limit
and and so it volition override any limit
that was ready previously. And if you want to become the size for all request records you can use total_count
method:
User . count #=> 1000 a = User . limit ( 5 ) ; a . count #=> five a . folio ( 1 ) . per ( 20 ) . size #=> 20 a . page ( one ) . per ( 20 ) . total_count #=> chiliad
The padding
Scope
Occasionally yous need to pad a number of records that is not a multiple of the page size.
User . order ( :proper name ) . page ( 7 ) . per ( fifty ) . padding ( three )
Note that the padding
scope as well is not directly divers on the models.
Unscoping
If for some reason yous need to unscope page
and per
methods you lot tin call except(:limit, :offset)
users = User . order ( :proper name ) . page ( seven ) . per ( l ) unpaged_users = users . except ( :limit , :offset ) # unpaged_users will not apply the kaminari scopes
Configuring Kaminari
General Configuration Options
Yous can configure the following default values past overriding these values using Kaminari.configure
method.
default_per_page # 25 by default max_per_page # nil past default max_pages # nil by default window # four by default outer_window # 0 by default left # 0 by default correct # 0 past default page_method_name # :page past default param_name # :folio by default params_on_first_page # faux by default
There's a handy generator that generates the default configuration file into config/initializers directory. Run the following generator command, then edit the generated file.
% rails g kaminari:config
Changing page_method_name
You lot tin can change the method proper noun page
to bonzo
or plant
or whatever you similar, in order to play nice with existing folio
method or association or telescopic or any other plugin that defines page
method on your models.
Configuring Default per_page Value for Each Model by paginates_per
You can specify default per_page
value per each model using the following declarative DSL.
class User < ActiveRecord::Base paginates_per l terminate
Configuring Max per_page Value for Each Model by max_paginates_per
You can specify max per_page
value per each model using the following declarative DSL. If the variable that specified via per
scope is more than than this variable, max_paginates_per
is used instead of it. Default value is zero, which means you are not imposing whatever max per_page
value.
class User < ActiveRecord::Base max_paginates_per 100 stop
Configuring max_pages Value for Each Model by max_pages
You can specify max_pages
value per each model using the following declarative DSL. This value restricts the total number of pages that can be returned. Useful for setting limits on large collections.
class User < ActiveRecord::Base max_pages 100 cease
Configuring params_on_first_page when using ransack_memory
If you are using the ransack_memory
gem and experience problems navigating back to the previous or offset page, fix the params_on_first_page
setting to truthful
.
Controllers
The Folio Parameter Is in params[:page]
Typically, your controller code will look like this:
@users = User . order ( :name ) . folio params [ :page ]
Views
The Same Former Helper Method
Only telephone call the paginate
helper:
This volition return several ?page=N
pagination links surrounded by an HTML5 <nav>
tag.
Helpers
The paginate
Helper Method
This would output several pagination links such every bit « First ‹ Prev ... 2 three 4 5 6 seven eight 9 x ... Side by side › Concluding »
Specifying the "inner window" Size (4 by default)
<%= paginate @users, window: 2 %>
This would output something like ... five 6 7 8 9 ...
when 7 is the electric current page.
Specifying the "outer window" Size (0 past default)
<%= paginate @users, outer_window: 3 %>
This would output something like 1 2 iii ...(snip)... 18 19 20
while having 20 pages in full.
Outer Window Can Be Separately Specified by left, right (0 past default)
<%= paginate @users, left: ane, right: 3 %>
This would output something similar ane ...(snip)... 18 19 20
while having 20 pages in total.
Changing the Parameter Proper noun (:param_name
) for the Links
<%= paginate @users, param_name: :pagina %>
This would modify the query parameter proper name on each links.
Actress Parameters (:params
) for the Links
<%= paginate @users, params: {controller: 'foo', action: 'bar', format: :turbo_stream} %>
This would modify each link's url_option
. :controller
and :activity
might be the keys in common.
Ajax Links (crazy simple, but works perfectly!)
<%= paginate @users, remote: true %>
This would add data-remote="true"
to all the links inside.
Specifying an Alternative Views Directory (default is kaminari/)
<%= paginate @users, views_prefix: 'templates' %>
This would search for partials in app/views/templates/kaminari
. This option makes it easier to do things like A/B testing pagination templates/themes, using new/old templates at the same time besides as better integration with other gems such as cells.
The link_to_next_page
and link_to_previous_page
(aliased to link_to_prev_page
) Helper Methods
<%= link_to_next_page @items, 'Next Page' %>
This simply renders a link to the adjacent page. This would exist helpful for creating a Twitter-like pagination feature.
The helper methods support a params
pick to farther specify the link. If format
needs to be set up, inlude it in the params
hash.
<%= link_to_next_page @items, 'Adjacent Page', params: {controller: 'foo', action: 'bar', format: :turbo_stream} %>
The page_entries_info
Helper Method
<%= page_entries_info @posts %>
This renders a helpful message with numbers of displayed vs. total entries.
By default, the message will use the humanized class name of objects in collection: for instance, "projection types" for ProjectType models. The namespace will be cut out and only the last name will exist used. Override this with the :entry_name
parameter:
<%= page_entries_info @posts, entry_name: 'item' %> #=> Displaying items 6 - 10 of 26 in total
The rel_next_prev_link_tags
Helper Method
<%= rel_next_prev_link_tags @users %>
This renders the rel next and prev link tags for the head.
The path_to_next_page
Helper Method
<%= path_to_next_page @users %>
This returns the server relative path to the side by side page.
The path_to_prev_page
Helper Method
<%= path_to_prev_page @users %>
This returns the server relative path to the previous page.
I18n and Labels
The default labels for 'showtime', 'last', 'previous', '...' and 'side by side' are stored in the I18n yaml inside the engine, and rendered through I18n API. You tin can switch the label value per I18n.locale for your internationalized awarding. Keys and the default values are the following. You can override them by adding to a YAML file in your Runway.root/config/locales
directory.
en: views: pagination: offset: "« First" last: "Last »" previous: "‹ Prev" next: "Next ›" truncate: "…" helpers: page_entries_info: one_page: display_entries: nil: "No %{entry_name} found" one: "Displaying <b>1</b> %{entry_name}" other: "Displaying <b>all %{count}</b> %{entry_name}" more_pages: display_entries: "Displaying %{entry_name} <b>%{first} - %{terminal}</b> of <b>%{full}</b> in full"
If you use not-English localization come across i18n rules for changing one_page:display_entries
block.
Customizing the Pagination Helper
Kaminari includes a handy template generator.
To Edit Your Paginator
Run the generator beginning,
% track yard kaminari:views default
and then edit the partials in your app'south app/views/kaminari/
directory.
For Haml/Slim Users
Yous tin utilize the html2haml gem or the html2slim gem to convert erb templates. The kaminari jewel will automatically pick up haml/slim templates if you place them in app/views/kaminari/
.
Multiple Templates
In example you need different templates for your paginator (for example public and admin), y'all can pass --views-prefix directory
like this:
% rails g kaminari:views default --views-prefix admin
that will generate partials in app/views/admin/kaminari/
directory.
Themes
The generator has the power to fetch several sample template themes from the external repository (https://github.com/amatsuda/kaminari_themes) in addition to the arranged "default" one, which volition help you creating a nice looking paginator.
% rails g kaminari:views THEME
To see the full list of available themes, take a await at the themes repository, or just hit the generator without specifying THEME
argument.
Multiple Themes
To utilize multiple themes from within a single awarding, create a directory inside the app/views/kaminari/ and motility your custom template files into that directory.
% rails g kaminari:views default (skip if you have existing kaminari views) % cd app/views/kaminari % mkdir my_custom_theme % cp _*.html.* my_custom_theme/
Next, reference that directory when calling the paginate
method:
<%= paginate @users, theme: 'my_custom_theme' %>
Customize away!
Notation: if the theme isn't nowadays or none is specified, kaminari will default dorsum to the views included inside the jewel.
Paginating Without Issuing SELECT COUNT Query
Generally the paginator needs to know the full number of records to display the links, just sometimes we don't need the full number of records and just need the "previous folio" and "adjacent page" links. For such use example, Kaminari provides without_count
mode that creates a paginatable drove without counting the number of all records. This may be helpful when you lot're dealing with a very big dataset considering counting on a big table tends to go irksome on RDBMS.
Simply add .without_count
to your paginated object:
User . page ( 3 ) . without_count
In your view file, you lot tin simply use simple helpers like the following instead of the full-featured paginate
helper:
<%= link_to_prev_page @users, 'Previous Folio' %> <%= link_to_next_page @users, 'Side by side Page' %>
Paginating a Generic Assortment object
Kaminari provides an Array wrapper class that adapts a generic Array object to the paginate
view helper. However, the paginate
helper doesn't automatically handle your Assortment object (this is intentional and past blueprint). Kaminari::paginate_array
method converts your Array object into a paginatable Array that accepts page
method.
@paginatable_array = Kaminari . paginate_array ( my_array_object ) . folio ( params [ :page ] ) . per ( 10 )
You lot can specify the total_count
value through options Hash. This would be helpful when handling an Array-ish object that has a unlike count
value from actual count
such every bit RSolr search result or when you need to generate a custom pagination. For case:
@paginatable_array = Kaminari . paginate_array ( [ ] , total_count: 145 ) . folio ( params [ :page ] ) . per ( 10 )
or, in the instance of using an external API to source the page of data:
page_size = 10 one_page = get_page_of_data params [ :page ] , page_size @paginatable_array = Kaminari . paginate_array ( one_page . data , total_count: one_page . total_count ) . page ( params [ :page ] ) . per ( page_size )
Creating Friendly URLs and Caching
Because of the page
parameter and Rails routing, you can easily generate SEO and user-friendly URLs. For any resource you'd similar to paginate, merely add the following to your routes.rb
:
resource :my_resources do get 'page/:page' , action: :index , on: :collection end
If y'all are using Rails 4 or later, you can simplify route definitions by using business organization
:
concern :paginatable practise become '(folio/:page)' , action: :alphabetize , on: :collection , as: '' end resources :my_resources , concerns: :paginatable
This will create URLs like /my_resources/folio/33
instead of /my_resources?folio=33
. This is now a friendly URL, but it also has other added benefits...
Because the page
parameter is now a URL segment, we tin leverage on Rails page caching!
NOTE: In this example, I've pointed the route to my :index
activity. You may have defined a custom pagination activity in your controller - y'all should point action: :your_custom_action
instead.
Other Framework/Library Support
The kaminari gem
Technically, the kaminari gem consists of 3 private components:
kaminari-core: the cadre pagination logic kaminari-activerecord: Active Record adapter kaminari-actionview: Action View adapter
So, bundling gem 'kaminari'
is equivalent to the following 2 lines (kaminari-core is referenced from the adapters):
precious stone 'kaminari-activerecord' gem 'kaminari-actionview'
For Other ORM Users
If y'all want to use other supported ORMs instead of ActiveRecord, for example Mongoid, bundle its adapter instead of kaminari-activerecord.
gem 'kaminari-mongoid' precious stone 'kaminari-actionview'
Kaminari currently provides adapters for the following ORMs:
- Agile Tape: https://github.com/kaminari/kaminari/tree/chief/kaminari-activerecord (included in this repo)
- Mongoid: https://github.com/kaminari/kaminari-mongoid
- MongoMapper: https://github.com/kaminari/kaminari-mongo_mapper
- DataMapper: https://github.com/kaminari/kaminari-data_mapper (would not work on kaminari ane.0.ten)
For Other Web Framework Users
If y'all want to utilize other web frameworks instead of Rails + Action View, for example Sinatra, parcel its adapter instead of kaminari-actionview.
gem 'kaminari-activerecord' gem 'kaminari-sinatra'
Kaminari currently provides adapters for the post-obit web frameworks:
- Activity View: https://github.com/kaminari/kaminari/tree/master/kaminari-actionview (included in this repo)
- Sinatra: https://github.com/kaminari/kaminari-sinatra
- Grape: https://github.com/kaminari/kaminari-grape
For More Data
Cheque out Kaminari recipes on the GitHub Wiki for more advanced tips and techniques. https://github.com/kaminari/kaminari/wiki/Kaminari-recipes
Questions, Feedback
Experience free to message me on Github (amatsuda) or Twitter (@a_matsuda) ☇☇☇ :)
Contributing to Kaminari
Fork, set up, then send a pull request.
To run the test suite locally confronting all supported frameworks:
% bundle install % rake examination:all
To target the test suite confronting one framework:
% rake test:active_record_50
Yous tin can find a listing of supported test tasks by running rake -T
. You may as well find it useful to run a specific test for a specific framework. To exercise so, you'll accept to commencement make certain yous have bundled everything for that configuration, then you can run the specific examination:
% BUNDLE_GEMFILE= 'gemfiles/active_record_50.gemfile' parcel install % BUNDLE_GEMFILE= 'gemfiles/active_record_50.gemfile' Exam=kaminari-core/examination/requests/navigation_test.rb package exec rake test
Copyright
Copyright (c) 2011- Akira Matsuda. Encounter MIT-LICENSE for further details.
Source: https://github.com/kaminari/kaminari
0 Response to "How to Pass a Filter Param to a Read More Link_to Pagination, Rails"
Post a Comment