Skip to content

Instantly share code, notes, and snippets.

@MyklClason
Last active June 5, 2019 20:35
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save MyklClason/e4dc96fd0e009b7b3a9c84ddbb1e11d2 to your computer and use it in GitHub Desktop.
Save MyklClason/e4dc96fd0e009b7b3a9c84ddbb1e11d2 to your computer and use it in GitHub Desktop.
Search/Sort/Paginate with Ransack and Kaminari
<% models = @model.order(:name).page(params[:page]) %>
<% fields = @model.pluck(:field, :field).compact.uniq.sort %>
<% sort_order_field = [:field] %>
<%= search_form_for @search, remote: true, url: request.path, :method => :get,
id: 'model-form',
onchange: "$('#model-form').submit();" do |f| %>
<h1>Model <%= f.submit 'Search', class: 'inline btn btn-primary' %></h1>
<table class="table table-striped table-bordered table-condensed table-hover">
<thead>
<tr>
<th class="text-center"><%= sort_link @search, :searchable, sort_order_field, "Searchable", remote: true, method: :get %></th>
<th class="text-center"><%= sort_link @search, :field, sort_order_field, "Field", remote: true, method: :get %></th>
</tr>
<tr>
<th><%= f.search_field :searchable_cont %></th>
<th><%= f.select :field_cont, fields, include_blank: true %></th>
</tr>
</thead>
<tbody>
<% model.each do |model| %>
<tr>
<td><%= model.try(:searchable) %></td>
<td><%= model.try(:field) %></td>
</tr>
<% end %>
</tbody>
</table>
<% end %>
<%= paginate models %>
<p><%= page_entries_info models, :entry_name => 'model' %></p>
...
<div id="model">
<%= render 'model/listing' %>
</div>
...
$('#model').html('<%= escape_javascript(render partial: 'model/listing') %>');
$("input").change(function() {
$(this).val($(this).val().replace(/\s/g,""));
});
...
gem 'kaminari'
gem 'ransack'
..
class ModelController < ApplicationController
def action
@search = Model.ransack(params[:q])
# Display search results for current user
@models = @search.result
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment