diff --git a/404.html b/404.html index 6a9c87b..2905b05 100644 --- a/404.html +++ b/404.html @@ -6,13 +6,13 @@ Page Not Found | Ransack documentation - +
Skip to main content

Page Not Found

We could not find what you were looking for.

Please contact the owner of the site that linked you to the original URL and let them know their link is broken.

- + \ No newline at end of file diff --git a/assets/js/7bc87c9b.14f6820b.js b/assets/js/7bc87c9b.14f6820b.js new file mode 100644 index 0000000..2a4ac78 --- /dev/null +++ b/assets/js/7bc87c9b.14f6820b.js @@ -0,0 +1 @@ +"use strict";(self.webpackChunkdocs_website=self.webpackChunkdocs_website||[]).push([[382],{3905:function(e,t,n){n.d(t,{Zo:function(){return s},kt:function(){return f}});var r=n(7294);function o(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function a(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),n.push.apply(n,r)}return n}function i(e){for(var t=1;t=0||(o[n]=e[n]);return o}(e,t);if(Object.getOwnPropertySymbols){var a=Object.getOwnPropertySymbols(e);for(r=0;r=0||Object.prototype.propertyIsEnumerable.call(e,n)&&(o[n]=e[n])}return o}var l=r.createContext({}),u=function(e){var t=r.useContext(l),n=t;return e&&(n="function"==typeof e?e(t):i(i({},t),e)),n},s=function(e){var t=u(e.components);return r.createElement(l.Provider,{value:t},e.children)},p={inlineCode:"code",wrapper:function(e){var t=e.children;return r.createElement(r.Fragment,{},t)}},d=r.forwardRef((function(e,t){var n=e.components,o=e.mdxType,a=e.originalType,l=e.parentName,s=c(e,["components","mdxType","originalType","parentName"]),d=u(n),f=o,m=d["".concat(l,".").concat(f)]||d[f]||p[f]||a;return n?r.createElement(m,i(i({ref:t},s),{},{components:n})):r.createElement(m,i({ref:t},s))}));function f(e,t){var n=arguments,o=t&&t.mdxType;if("string"==typeof e||o){var a=n.length,i=new Array(a);i[0]=d;var c={};for(var l in t)hasOwnProperty.call(t,l)&&(c[l]=t[l]);c.originalType=e,c.mdxType="string"==typeof e?e:o,i[1]=c;for(var u=2;u=0||(o[n]=e[n]);return o}(e,t);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(e);for(r=0;r=0||Object.prototype.propertyIsEnumerable.call(e,n)&&(o[n]=e[n])}return o}var l=r.createContext({}),u=function(e){var t=r.useContext(l),n=t;return e&&(n="function"==typeof e?e(t):a(a({},t),e)),n},s=function(e){var t=u(e.components);return r.createElement(l.Provider,{value:t},e.children)},p={inlineCode:"code",wrapper:function(e){var t=e.children;return r.createElement(r.Fragment,{},t)}},d=r.forwardRef((function(e,t){var n=e.components,o=e.mdxType,i=e.originalType,l=e.parentName,s=c(e,["components","mdxType","originalType","parentName"]),d=u(n),m=o,f=d["".concat(l,".").concat(m)]||d[m]||p[m]||i;return n?r.createElement(f,a(a({ref:t},s),{},{components:n})):r.createElement(f,a({ref:t},s))}));function m(e,t){var n=arguments,o=t&&t.mdxType;if("string"==typeof e||o){var i=n.length,a=new Array(i);a[0]=d;var c={};for(var l in t)hasOwnProperty.call(t,l)&&(c[l]=t[l]);c.originalType=e,c.mdxType="string"==typeof e?e:o,a[1]=c;for(var u=2;u=r)&&Object.keys(o.O).every((function(e){return o.O[e](n[u])}))?n.splice(u--,1):(a=!1,r0&&e[b-1][2]>r;b--)e[b]=e[b-1];e[b]=[n,f,r]},o.n=function(e){var t=e&&e.__esModule?function(){return e.default}:function(){return e};return o.d(t,{a:t}),t},n=Object.getPrototypeOf?function(e){return Object.getPrototypeOf(e)}:function(e){return e.__proto__},o.t=function(e,f){if(1&f&&(e=this(e)),8&f)return e;if("object"==typeof e&&e){if(4&f&&e.__esModule)return e;if(16&f&&"function"==typeof e.then)return e}var r=Object.create(null);o.r(r);var c={};t=t||[null,n({}),n([]),n(n)];for(var a=2&f&&e;"object"==typeof a&&!~t.indexOf(a);a=n(a))Object.getOwnPropertyNames(a).forEach((function(t){c[t]=function(){return e[t]}}));return c.default=function(){return e},o.d(r,c),r},o.d=function(e,t){for(var n in t)o.o(t,n)&&!o.o(e,n)&&Object.defineProperty(e,n,{enumerable:!0,get:t[n]})},o.f={},o.e=function(e){return Promise.all(Object.keys(o.f).reduce((function(t,n){return o.f[n](e,t),t}),[]))},o.u=function(e){return"assets/js/"+({13:"01a85c17",15:"eae51d00",53:"935f2afb",84:"07f9f2ec",85:"1f391b9e",89:"a6aa9e1f",103:"ccc49370",168:"dffbd312",197:"bb5657b1",230:"2bc2bb50",245:"0d4fa94e",260:"b1e4a2bb",274:"72c2091b",324:"29104dc6",341:"da250cee",364:"8c747907",382:"7bc87c9b",395:"764f00df",407:"7bf2db17",414:"393be207",436:"009f1e98",474:"fc57f22d",491:"9fa839ec",510:"b8ab82ee",514:"1be78505",535:"814f3328",570:"31a91795",591:"92fe0e90",597:"db1f0725",600:"9c504410",608:"9e4087bc",610:"6875c492",671:"0e384e19",699:"ce7a2be6",719:"4eaee7fa",782:"460f2046",841:"3fbeb73f",843:"e3caf117",896:"a38d0388",918:"17896441",939:"01befa62",944:"99efcd31",953:"d4672cd7"}[e]||e)+"."+{13:"9208edce",15:"b4864371",53:"fd385b63",75:"6c4ea5d2",84:"51ef5241",85:"649fb2eb",89:"a15f69ad",103:"ec69d97c",168:"982d70b5",197:"568bff85",230:"7c4542fa",245:"87228abe",260:"a508f449",274:"68e67613",324:"06106596",341:"ee632a26",364:"ed9da322",382:"f53de1ac",395:"e2796df4",407:"2090e87f",414:"fa4d0ba8",436:"f4352517",459:"35f72554",474:"5cda7080",491:"748e1a86",510:"c1ae267c",514:"660ad521",535:"a207ff00",570:"503f461d",591:"168e7891",597:"0cfae94d",600:"95360987",608:"99b7839a",610:"906c3181",671:"4c917cae",699:"c8bcc6cf",719:"fb1f4e3c",782:"16ba1dfc",841:"557146f3",843:"1c6c21c1",896:"c20b105d",918:"5557c43f",939:"cdfcafc1",944:"9bfb592e",953:"cb52586c"}[e]+".js"},o.miniCssF=function(e){},o.g=function(){if("object"==typeof globalThis)return globalThis;try{return this||new Function("return this")()}catch(e){if("object"==typeof window)return window}}(),o.o=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},f={},r="docs-website:",o.l=function(e,t,n,c){if(f[e])f[e].push(t);else{var a,u;if(void 0!==n)for(var i=document.getElementsByTagName("script"),b=0;b=r)&&Object.keys(o.O).every((function(e){return o.O[e](n[u])}))?n.splice(u--,1):(a=!1,r0&&e[b-1][2]>r;b--)e[b]=e[b-1];e[b]=[n,f,r]},o.n=function(e){var t=e&&e.__esModule?function(){return e.default}:function(){return e};return o.d(t,{a:t}),t},n=Object.getPrototypeOf?function(e){return Object.getPrototypeOf(e)}:function(e){return e.__proto__},o.t=function(e,f){if(1&f&&(e=this(e)),8&f)return e;if("object"==typeof e&&e){if(4&f&&e.__esModule)return e;if(16&f&&"function"==typeof e.then)return e}var r=Object.create(null);o.r(r);var c={};t=t||[null,n({}),n([]),n(n)];for(var a=2&f&&e;"object"==typeof a&&!~t.indexOf(a);a=n(a))Object.getOwnPropertyNames(a).forEach((function(t){c[t]=function(){return e[t]}}));return c.default=function(){return e},o.d(r,c),r},o.d=function(e,t){for(var n in t)o.o(t,n)&&!o.o(e,n)&&Object.defineProperty(e,n,{enumerable:!0,get:t[n]})},o.f={},o.e=function(e){return Promise.all(Object.keys(o.f).reduce((function(t,n){return o.f[n](e,t),t}),[]))},o.u=function(e){return"assets/js/"+({13:"01a85c17",15:"eae51d00",53:"935f2afb",84:"07f9f2ec",85:"1f391b9e",89:"a6aa9e1f",103:"ccc49370",168:"dffbd312",197:"bb5657b1",230:"2bc2bb50",245:"0d4fa94e",260:"b1e4a2bb",274:"72c2091b",324:"29104dc6",341:"da250cee",364:"8c747907",382:"7bc87c9b",395:"764f00df",407:"7bf2db17",414:"393be207",436:"009f1e98",474:"fc57f22d",491:"9fa839ec",510:"b8ab82ee",514:"1be78505",535:"814f3328",570:"31a91795",591:"92fe0e90",597:"db1f0725",600:"9c504410",608:"9e4087bc",610:"6875c492",671:"0e384e19",699:"ce7a2be6",719:"4eaee7fa",782:"460f2046",841:"3fbeb73f",843:"e3caf117",896:"a38d0388",918:"17896441",939:"01befa62",944:"99efcd31",953:"d4672cd7"}[e]||e)+"."+{13:"9208edce",15:"b4864371",53:"fd385b63",75:"6c4ea5d2",84:"51ef5241",85:"649fb2eb",89:"a15f69ad",103:"ec69d97c",168:"982d70b5",197:"568bff85",230:"7c4542fa",245:"87228abe",260:"a508f449",274:"68e67613",324:"06106596",341:"ee632a26",364:"ed9da322",382:"14f6820b",395:"e2796df4",407:"2090e87f",414:"fa4d0ba8",436:"f4352517",459:"35f72554",474:"5cda7080",491:"748e1a86",510:"c1ae267c",514:"660ad521",535:"a207ff00",570:"503f461d",591:"168e7891",597:"0cfae94d",600:"95360987",608:"99b7839a",610:"906c3181",671:"4c917cae",699:"c8bcc6cf",719:"fb1f4e3c",782:"16ba1dfc",841:"557146f3",843:"1c6c21c1",896:"c20b105d",918:"5557c43f",939:"cdfcafc1",944:"9bfb592e",953:"cb52586c"}[e]+".js"},o.miniCssF=function(e){},o.g=function(){if("object"==typeof globalThis)return globalThis;try{return this||new Function("return this")()}catch(e){if("object"==typeof window)return window}}(),o.o=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},f={},r="docs-website:",o.l=function(e,t,n,c){if(f[e])f[e].push(t);else{var a,u;if(void 0!==n)for(var i=document.getElementsByTagName("script"),b=0;b Blog | Ransack documentation - +

· 2 min read

Ransack has been a part of many Rubyists toolboxes for years and 3.0.0 is a major release. We have a number of new features and one breaking change. As part of 3.0.0, we decided to launch this documentation website, merging in the Wiki and the content from the README.

With 3.0.0 we are hoping to re-energise the community, we need help on closing out old issues, refactoring the codebase and even some design work.

I also wanted to let you know that Ernie Miller (creator of Ransack) has decided to leave the project completely, he has this message for the community:

While my own personal development efforts have been spent elsewhere as of late, I'm keenly aware of how many people still depend on some of the software I originally wrote all those years ago.

That's why I'm grateful to be able to step away from the ActiveRecord Hackery organization (and, specifically, maintenance of Ransack) without impacting those users. I'm thankful that Sean, David, Greg, and others will continue to support users, and wish them the best as they move forward without me!

Please join me in thanking Ernie for bringing Ransack to life, I personally think it is one of the most amazing Rails libraries out there.

- + \ No newline at end of file diff --git a/blog/archive.html b/blog/archive.html index d654df1..9ec629a 100644 --- a/blog/archive.html +++ b/blog/archive.html @@ -6,13 +6,13 @@ Archive | Ransack documentation - + - + \ No newline at end of file diff --git a/blog/ransack-3-0-0.html b/blog/ransack-3-0-0.html index c2c85de..69d8172 100644 --- a/blog/ransack-3-0-0.html +++ b/blog/ransack-3-0-0.html @@ -6,13 +6,13 @@ Ransack 3.0.0 | Ransack documentation - +

Ransack 3.0.0

· 2 min read

Ransack has been a part of many Rubyists toolboxes for years and 3.0.0 is a major release. We have a number of new features and one breaking change. As part of 3.0.0, we decided to launch this documentation website, merging in the Wiki and the content from the README.

With 3.0.0 we are hoping to re-energise the community, we need help on closing out old issues, refactoring the codebase and even some design work.

I also wanted to let you know that Ernie Miller (creator of Ransack) has decided to leave the project completely, he has this message for the community:

While my own personal development efforts have been spent elsewhere as of late, I'm keenly aware of how many people still depend on some of the software I originally wrote all those years ago.

That's why I'm grateful to be able to step away from the ActiveRecord Hackery organization (and, specifically, maintenance of Ransack) without impacting those users. I'm thankful that Sean, David, Greg, and others will continue to support users, and wish them the best as they move forward without me!

Please join me in thanking Ernie for bringing Ransack to life, I personally think it is one of the most amazing Rails libraries out there.

- + \ No newline at end of file diff --git a/blog/tags.html b/blog/tags.html index da74068..d9ba79f 100644 --- a/blog/tags.html +++ b/blog/tags.html @@ -6,13 +6,13 @@ Tags | Ransack documentation - + - + \ No newline at end of file diff --git a/blog/tags/ransack.html b/blog/tags/ransack.html index 4075fd5..70d4017 100644 --- a/blog/tags/ransack.html +++ b/blog/tags/ransack.html @@ -6,13 +6,13 @@ One post tagged with "ransack" | Ransack documentation - +

One post tagged with "ransack"

View All Tags

· 2 min read

Ransack has been a part of many Rubyists toolboxes for years and 3.0.0 is a major release. We have a number of new features and one breaking change. As part of 3.0.0, we decided to launch this documentation website, merging in the Wiki and the content from the README.

With 3.0.0 we are hoping to re-energise the community, we need help on closing out old issues, refactoring the codebase and even some design work.

I also wanted to let you know that Ernie Miller (creator of Ransack) has decided to leave the project completely, he has this message for the community:

While my own personal development efforts have been spent elsewhere as of late, I'm keenly aware of how many people still depend on some of the software I originally wrote all those years ago.

That's why I'm grateful to be able to step away from the ActiveRecord Hackery organization (and, specifically, maintenance of Ransack) without impacting those users. I'm thankful that Sean, David, Greg, and others will continue to support users, and wish them the best as they move forward without me!

Please join me in thanking Ernie for bringing Ransack to life, I personally think it is one of the most amazing Rails libraries out there.

- + \ No newline at end of file diff --git a/blog/tags/release.html b/blog/tags/release.html index 24ce288..7a97439 100644 --- a/blog/tags/release.html +++ b/blog/tags/release.html @@ -6,13 +6,13 @@ One post tagged with "release" | Ransack documentation - +

One post tagged with "release"

View All Tags

· 2 min read

Ransack has been a part of many Rubyists toolboxes for years and 3.0.0 is a major release. We have a number of new features and one breaking change. As part of 3.0.0, we decided to launch this documentation website, merging in the Wiki and the content from the README.

With 3.0.0 we are hoping to re-energise the community, we need help on closing out old issues, refactoring the codebase and even some design work.

I also wanted to let you know that Ernie Miller (creator of Ransack) has decided to leave the project completely, he has this message for the community:

While my own personal development efforts have been spent elsewhere as of late, I'm keenly aware of how many people still depend on some of the software I originally wrote all those years ago.

That's why I'm grateful to be able to step away from the ActiveRecord Hackery organization (and, specifically, maintenance of Ransack) without impacting those users. I'm thankful that Sean, David, Greg, and others will continue to support users, and wish them the best as they move forward without me!

Please join me in thanking Ernie for bringing Ransack to life, I personally think it is one of the most amazing Rails libraries out there.

- + \ No newline at end of file diff --git a/getting-started/advanced-mode.html b/getting-started/advanced-mode.html index 5eb0d99..6ec59b2 100644 --- a/getting-started/advanced-mode.html +++ b/getting-started/advanced-mode.html @@ -6,7 +6,7 @@ Advanced Mode | Ransack documentation - + @@ -20,7 +20,7 @@ the HTTP POST method instead of GET.

sort_url

Ransack's sort_url helper is like a sort_link but returns only the url

sort_url has the same API as sort_link:

<%= sort_url(@q, :name, default_order: :desc) %>
<%= sort_url(@q, :last_name, [:last_name, 'first_name asc']) %>
<%= sort_url(@q, :last_name, %i(last_name first_name),
default_order: { last_name: 'asc', first_name: 'desc' }) %>

PostgreSQL's sort option

The NULLS FIRST and NULLS LAST options can be used to determine whether nulls appear before or after non-null values in the sort ordering.

You may want to configure it like this:

Ransack.configure do |c|
c.postgres_fields_sort_option = :nulls_first # or :nulls_last
end

To treat nulls as having the lowest or highest value respectively. To force nulls to always be first or last, use

Ransack.configure do |c|
c.postgres_fields_sort_option = :nulls_always_first # or :nulls_always_last
end

See this feature: https://www.postgresql.org/docs/13/queries-order.html

Case Insensitive Sorting in PostgreSQL

In order to request PostgreSQL to do a case insensitive sort for all string columns of a model at once, Ransack can be extended by using this approach:

module RansackObject

def self.included(base)
base.columns.each do |column|
if column.type == :string
base.ransacker column.name.to_sym, type: :string do
Arel.sql("lower(#{base.table_name}.#{column.name})")
end
end
end
end
end
class UserWithManyAttributes < ActiveRecord::Base
include RansackObject
end

If this approach is taken, it is advisable to add a functional index.

This was originally asked in a Ransack issue and a solution was found on Stack Overflow.

- + \ No newline at end of file diff --git a/getting-started/sorting.html b/getting-started/sorting.html index 5c01ce5..f4e6af6 100644 --- a/getting-started/sorting.html +++ b/getting-started/sorting.html @@ -6,13 +6,13 @@ Sorting | Ransack documentation - +

Sorting

Sorting in the View

You can add a form to capture sorting and filtering options together.

<div class="filters" id="filtersSidebar">
<header class="filters-header">
<div class="filters-header-content">
<h3>Filters</h3>
</div>
</header>

<div class="filters-content">
<%= search_form_for @q,
class: 'form',
url: articles_path,
html: { autocomplete: 'off', autocapitalize: 'none' } do |f| %>

<div class="form-group">
<%= f.label :title_cont, t('Filter_by_keyword') %>
<%= f.search_field :title_cont %>
</div>

<%= render partial: 'filters/date_title_sort', locals: { f: f } %>

<div class="form-group">
<%= f.label :grade_level_gteq, t('Grade_level') %> >=
<%= f.search_field :grade_level_gteq %>
</div>

<div class="form-group">
<%= f.label :readability_gteq, t('Readability') %> >=
<%= f.search_field :readability_gteq %>
</div>

<div class="form-group">
<i><%= @articles.total_count %> articles</i>
</div>

<div class="form-group">
<hr/>
<div class="filters-header-content">
<%= link_to request.path, class: 'form-link' do %>
<i class="far fa-undo icon-l"></i><%= t('Clear_all') %>
<% end %>

<%= f.submit t('Filter'), class: 'btn btn-primary' %>
</div>
</div>
<% end %>
</div>
</div>

Sorting in the Controller

To specify a default search sort field + order in the controller index:

@search = Post.ransack(params[:q])
@search.sorts = 'name asc' if @search.sorts.empty?
@posts = @search.result.paginate(page: params[:page], per_page: 20)

Multiple sorts can be set by:

@search = Post.ransack(params[:q])  
@search.sorts = ['name asc', 'created_at desc'] if @search.sorts.empty?
@posts = @search.result.paginate(page: params[:page], per_page: 20)
- + \ No newline at end of file diff --git a/getting-started/using-predicates.html b/getting-started/using-predicates.html index 053dfcc..f74ae6f 100644 --- a/getting-started/using-predicates.html +++ b/getting-started/using-predicates.html @@ -6,7 +6,7 @@ Using Predicates | Ransack documentation - + @@ -22,7 +22,7 @@ to Ransack that you indeed want to check the truthiness of this field. The other values are 'true', 'TRUE', 't' or 'T'.

>> User.ransack(awesome_true: '1').result.to_sql
=> SELECT "users".* FROM "users" WHERE ("users"."awesome" = 't')

Note: different database systems use different values to represent truth. In the above example, we are using SQLite3.

Opposite: not_true

false

The false predicate returns all records where a field is false.

>> User.ransack(awesome_false: '1').result.to_sql
=> SELECT "users".* FROM "users" WHERE ("users"."awesome" = 'f')

Opposite: not_false

Note: the false predicate may be considered the opposite of the true predicate if the field does not contain null values. Otherwise, use not_false.

present

The present predicate returns all records where a field is present (not null and not a blank string).

>> User.ransack(first_name_present: '1').result.to_sql
=> SELECT "users".* FROM "users" WHERE (("users"."first_name" IS NOT NULL AND "users"."first_name" != ''))

Opposite: blank

null

The null predicate returns all records where a field is null:

>> User.ransack(first_name_null: 1).result.to_sql
=> SELECT "users".* FROM "users" WHERE "users"."first_name" IS NULL

Opposite: not_null

URL parameter structure

The search parameters are passed to ransack as a hash. The URL representation of this hash uses the bracket notation: hash_name[key]=value. The hash_name is the parameter which is defined in the controller, for instance q. The key is the attribute and search predicate compound, for instance first_name_cont, the value is the search parameter. When searching without using the search form helpers this URL structure needs to be created manually.

For example, the URL layout for searching and sorting users could looks like this:

/users.json?q[first_name_cont]=pete&q[last_name_cont]=jack&q[s]=created_at+desc

Note that the sorting parameter s is nested within the q hash.

When using JavaScript to create such a URL, a matching jQuery request could look like this:

$.ajax({
url: "/users.json",
data: {
q: {
first_name_cont: "pete",
last_name_cont: "jack",
s: "created_at desc"
}
},
success: function (data){
console.log(data);
}
});
- + \ No newline at end of file diff --git a/going-further/associations.html b/going-further/associations.html index 1855092..d8a02e2 100644 --- a/going-further/associations.html +++ b/going-further/associations.html @@ -6,7 +6,7 @@ Associations | Ransack documentation - + @@ -15,7 +15,7 @@ associations.

Given these associations...

class Employee < ActiveRecord::Base
belongs_to :supervisor

# has attributes first_name:string and last_name:string
end

class Department < ActiveRecord::Base
has_many :supervisors

# has attribute title:string
end

class Supervisor < ActiveRecord::Base
belongs_to :department
has_many :employees

# has attribute last_name:string
end

... and a controller...

class SupervisorsController < ApplicationController
def index
@q = Supervisor.ransack(params[:q])
@supervisors = @q.result.includes(:department, :employees)
end
end

... you might set up your form like this...

<%= search_form_for @q do |f| %>
<%= f.label :last_name_cont %>
<%= f.search_field :last_name_cont %>

<%= f.label :department_title_cont %>
<%= f.search_field :department_title_cont %>

<%= f.label :employees_first_name_or_employees_last_name_cont %>
<%= f.search_field :employees_first_name_or_employees_last_name_cont %>

<%= f.submit "search" %>
<% end %>
...
<%= content_tag :table do %>
<%= content_tag :th, sort_link(@q, :last_name) %>
<%= content_tag :th, sort_link(@q, :department_title) %>
<%= content_tag :th, sort_link(@q, :employees_last_name) %>
<% end %>

If you have trouble sorting on associations, try using an SQL string with the pluralized table ('departments.title','employees.last_name') instead of the symbolized association (:department_title), :employees_last_name).

- + \ No newline at end of file diff --git a/going-further/custom-predicates.html b/going-further/custom-predicates.html index cd8f247..d54823d 100644 --- a/going-further/custom-predicates.html +++ b/going-further/custom-predicates.html @@ -6,13 +6,13 @@ Custom predicates | Ransack documentation - +

Custom predicates

If you'd like to add your own custom Ransack predicates:

# config/initializers/ransack.rb

Ransack.configure do |config|
config.add_predicate 'equals_diddly', # Name your predicate
# What non-compound ARel predicate will it use? (eq, matches, etc)
arel_predicate: 'eq',
# Format incoming values as you see fit. (Default: Don't do formatting)
formatter: proc { |v| "#{v}-diddly" },
# Validate a value. An "invalid" value won't be used in a search.
# Below is default.
validator: proc { |v| v.present? },
# Should compounds be created? Will use the compound (any/all) version
# of the arel_predicate to create a corresponding any/all version of
# your predicate. (Default: true)
compounds: true,
# Force a specific column type for type-casting of supplied values.
# (Default: use type from DB column)
type: :string,
# Use LOWER(column on database).
# (Default: false)
case_insensitive: true
end

You can check all Arel predicates here.

If Arel does not have the predicate you are looking for, consider monkey patching it:

# config/initializers/ransack.rb

module Arel
module Predications
def gteq_or_null(other)
left = gteq(other)
right = eq(nil)
left.or(right)
end
end
end

Ransack.configure do |config|
config.add_predicate 'gteq_or_null', arel_predicate: 'gteq_or_null'
end
- + \ No newline at end of file diff --git a/going-further/documentation.html b/going-further/documentation.html index 4504b4f..1dbba43 100644 --- a/going-further/documentation.html +++ b/going-further/documentation.html @@ -6,13 +6,13 @@ Documentation | Ransack documentation - +
-

Documentation

Ransack uses Docusaurus for documentation. To contribute to the docs simply use the "Edit this page" link from any page to directly edit, or else pull the repo and edit locally.

Local Development

cd docs
yarn start

This command starts a local development server and opens up a browser window. Most changes are reflected live without having to restart the server.

Build

yarn build

This command generates static content into the build directory and can be served using any static contents hosting service.

Deployment

Using SSH:

USE_SSH=true yarn deploy
- +

Documentation

Ransack uses Docusaurus for documentation. To contribute to the docs simply use the "Edit this page" link from any page to directly edit, or else pull the repo and edit locally.

Local Development

Switch to docs folder

cd docs

Install docusaurus and other dependencies

yarn install

Start a local development server and open up a browser window. Most changes are reflected live without having to restart the server.

yarn start

Build

yarn build

This command generates static content into the build directory and can be served using any static contents hosting service.

Deployment

Using SSH:

USE_SSH=true yarn deploy
+ \ No newline at end of file diff --git a/going-further/exporting-to-csv.html b/going-further/exporting-to-csv.html index 0f878fc..c8ec48e 100644 --- a/going-further/exporting-to-csv.html +++ b/going-further/exporting-to-csv.html @@ -6,13 +6,13 @@ CSV Export | Ransack documentation - +

CSV Export

Exporting to CSV

Example downloading a csv file preserving ransack search, based on this gist

index.html.erb
<h1>Users</h1>

<%= search_form_for @q, url: dashboard_index_path do |f| %>
<%= f.label :name_cont %>
<%= f.search_field :name_cont %>

<%= f.submit %>
<% end %>

<ul>
<% @users.each do |user| %>
<li><%= user.name %> [<%= user.devices.map {|device| device.name }.join(', ') %>]</li>
<% end %>
</ul>

<% if params[:q] %>
<%= link_to 'Export 1', dashboard_index_path({name: params[:q][:name_cont]}.merge({format: :csv})) %>
<% else %>
<%= link_to 'Export 2', dashboard_index_path(format: 'csv') %>
<% end %>
user.rb
require 'csv'

class User < ApplicationRecord
has_many :devices

def self.get_csv(users)
CSV.generate do |csv|
csv << ["Name", "Devices"]

users.each do |user|
csv << [user.name, user.devices.map{|device| device.name}.join(', ')]
end
end
end
end
- + \ No newline at end of file diff --git a/going-further/external-guides.html b/going-further/external-guides.html index 74629b3..2634fcc 100644 --- a/going-further/external-guides.html +++ b/going-further/external-guides.html @@ -6,14 +6,14 @@ External resources | Ransack documentation - +

External resources

There is a plethora of material on Ransack around the internet. We've collected some here for your convenience.

Do you want to have a blog post or other content on Ransack highlighted? Please just edit the page, add your content and a Pull Request will be sent to Ransack maintainers for approval.

Screencasts

Gems

  • ActiveAdmin The Administration Framework for Rails uses Ransack internally
  • Ransack Memory Automatically save and load Ransack's filtered params into the Rail's session
  • Mobility Ransack Search attributes translated by Mobility with Ransack.
  • Ransack UI Framework for building a search UI with Ransack seems abandoned

Blogs

In French

In Vietnamese

- + \ No newline at end of file diff --git a/going-further/form-customisation.html b/going-further/form-customisation.html index d4b8147..03fd017 100644 --- a/going-further/form-customisation.html +++ b/going-further/form-customisation.html @@ -6,13 +6,13 @@ Form customisation | Ransack documentation - +

Form customisation

Predicate and attribute labels in forms may be specified with I18n in a translation file (see the locale files in Ransack::Locale for more examples):

# locales/en.yml
en:
ransack:
asc: ascending
desc: descending
predicates:
cont: contains
not_cont: not contains
start: starts with
end: ends with
gt: greater than
lt: less than
attributes:
person:
name: Full Name
article:
title: Article Title
body: Main Content

The names of attribute fields may also be changed globally or under activerecord:

# locales/en.yml
en:
attributes:
model_name:
model_field1: field name1
model_field2: field name2
activerecord:
attributes:
namespace/article:
title: AR Namespaced Title
namespace_article:
title: Old Ransack Namespaced Title

To limit the predicates in the predicate_select form helper in a view template, pass an array of permitted predicates with only:

<%= f.predicate_select only: %i(cont not_cont eq not_eq blank null) %>

Compound predicates (_any & _all) may be removed by passing the option compounds: false.

<%= f.predicate_select compounds: false %>

Searchable attributes versus non-searchable ones may be specified as follows:

def self.ransackable_attributes(auth_object = nil)
%w(searchable_attribute_1 searchable_attribute_2 ...) + _ransackers.keys
end
- + \ No newline at end of file diff --git a/going-further/i18n.html b/going-further/i18n.html index ae8e8a5..29d599d 100644 --- a/going-further/i18n.html +++ b/going-further/i18n.html @@ -6,7 +6,7 @@ i18n | Ransack documentation - + @@ -16,7 +16,7 @@ many translations for Ransack available at http://www.localeapp.com/projects/2999.

Predicate and attribute translations in forms may be specified as follows (see the translation files in Ransack::Locale for more examples):

locales/en.yml:

en:
ransack:
asc: ascending
desc: descending
predicates:
cont: contains
not_cont: not contains
start: starts with
end: ends with
gt: greater than
lt: less than
models:
person: Passanger
attributes:
person:
name: Full Name
article:
title: Article Title
body: Main Content

Attribute names may also be changed globally, or under activerecord:

en:
attributes:
model_name:
model_field1: field name1
model_field2: field name2
activerecord:
attributes:
namespace/article:
title: AR Namespaced Title
namespace_article:
title: Old Ransack Namespaced Title
- + \ No newline at end of file diff --git a/going-further/merging-searches.html b/going-further/merging-searches.html index 9e49223..e832f76 100644 --- a/going-further/merging-searches.html +++ b/going-further/merging-searches.html @@ -6,13 +6,13 @@ Merging searches | Ransack documentation - +

Merging searches

To find records that match multiple searches, it's possible to merge all the ransack search conditions into an ActiveRecord relation to perform a single query. In order to avoid conflicts between joined table names it's necessary to set up a shared context to track table aliases used across all the conditions before initializing the searches:

shared_context = Ransack::Context.for(Person)

search_parents = Person.ransack(
{ parent_name_eq: "A" }, context: shared_context
)

search_children = Person.ransack(
{ children_name_eq: "B" }, context: shared_context
)

shared_conditions = [search_parents, search_children].map { |search|
Ransack::Visitor.new.accept(search.base)
}

Person.joins(shared_context.join_sources)
.where(shared_conditions.reduce(&:or))
.to_sql

Produces:

SELECT "people".*
FROM "people"
LEFT OUTER JOIN "people" "parents_people"
ON "parents_people"."id" = "people"."parent_id"
LEFT OUTER JOIN "people" "children_people"
ON "children_people"."parent_id" = "people"."id"
WHERE (
("parents_people"."name" = 'A' OR "children_people"."name" = 'B')
)
ORDER BY "people"."id" DESC

Admittedly this is not as simple as it should be, but it's workable for now. (Implementing #417 could make this more straightforward.)

- + \ No newline at end of file diff --git a/going-further/other-notes.html b/going-further/other-notes.html index ea208e5..eadeee0 100644 --- a/going-further/other-notes.html +++ b/going-further/other-notes.html @@ -6,7 +6,7 @@ Other notes | Ransack documentation - + @@ -77,7 +77,7 @@ Memberships, and many Musicians through Memberships:

require File.expand_path('../boot', __FILE__)
ENV['RANSACK_FORM_BUILDER'] = '::SimpleForm::FormBuilder'
require 'rails/all'
- + \ No newline at end of file diff --git a/going-further/ransackers.html b/going-further/ransackers.html index 525ff2a..0b4cbd1 100644 --- a/going-further/ransackers.html +++ b/going-further/ransackers.html @@ -6,7 +6,7 @@ Ransackers | Ransack documentation - + @@ -17,7 +17,7 @@ But for your Rails application 2019-07-18 01:21:29.826484 is Arguments may be passed to a ransacker method via ransacker_args:


class Person
ransacker :author_max_title_of_article_where_body_length_between,
args: [:parent, :ransacker_args] do |parent, args|
min, max = args
query = <<-SQL
(SELECT MAX(articles.title)
FROM articles
WHERE articles.person_id = people.id
AND CHAR_LENGTH(articles.body) BETWEEN #{min.to_i} AND #{max.to_i}
GROUP BY articles.person_id
)
SQL
Arel.sql(query)
end
end

# Usage
Person.ransack(
conditions: [{
attributes: {
'0' => {
name: 'author_max_title_of_article_where_body_length_between',
ransacker_args: [10, 100]
}
},
predicate_name: 'cont',
values: ['Ransackers can take arguments']
}]
)

=> SELECT "people".* FROM "people" WHERE (
(SELECT MAX(articles.title)
FROM articles
WHERE articles.person_id = people.id
AND CHAR_LENGTH(articles.body) BETWEEN 10 AND 100
GROUP BY articles.person_id
)
LIKE '%Ransackers can take arguments%')
ORDER BY "people"."id" DESC

Adding the attribute values associated with a column name to a searchable attribute in a dropdown options (instead of a traditional column name coming from a table). This is useful if using an associated table which is acting as a join table between a parent table and domain table. This will cache the data as the selections:

# in the model:
Model.pluck(:name).each do |ground|
ransacker ground.to_sym do |parent|
Arel::Nodes::InfixOperation.new('AND',
Arel::Nodes::InfixOperation.new('=', parent.table[:gor_name], ground),
parent.table[:status]
)
end
end

# This will not include the column names in the dropdown
def self.ransackable_attributes(auth_object = nil)
%w() + _ransackers.keys
end

Testing for existence

Testing for the existence of a row in another table via a join:

# in the model:
ransacker :price_exists do |parent|
# SQL syntax for PostgreSQL -- others may differ
# This returns boolean true or false
Arel.sql("(select exists (select 1 from prices where prices.book_id = books.id))")
end

In the view

  %td= f.select :price_exists_true, [["Any", 2], ["No", 0], ["Yes", 1]]

Associations

Performing a query on an association with a differing class name:

Say we have a model "SalesAccount", which represents a relationship between two users, one being designated as a "sales_rep". We want to query SalesAccounts by the name of the sales_rep:

# in the model:
class SalesAccount < ActiveRecord::Base
belongs_to :user
belongs_to :sales_rep, class_name: :User

# in the controller:
# The line below would lead to errors thrown later if not for the
# "joins(:sales_reps)".
@q = SalesAccount.includes(:user).joins(:sales_rep).ransack(params[:q])
@sales_accounts = @q.result(distinct: true)

In the view:

<%= f.search_field :sales_rep_name_start %>

Search on translations

Search for a translated value in a jsonb column:

Note: There is also a gem, Mobility Ransack, which allows you to search on translated attributes independent of their storage backend.

This will work with any jsonb data type. In this case I have a column translated with Mobility called name with the value {'en': "Hello", 'es': "Hola"}.

ransacker :name do |parent|    
Arel::Nodes::InfixOperation.new('->>', parent.table[:name], Arel::Nodes.build_quoted(Mobility.locale))
end

If using Rails 4.1 or under, remove the build_quoted call.

You can then search for name_eq or name_cont and it will do the proper SQL.


Please feel free to contribute further code examples!

- + \ No newline at end of file diff --git a/going-further/release_process.html b/going-further/release_process.html index 5dec131..f65cf03 100644 --- a/going-further/release_process.html +++ b/going-further/release_process.html @@ -6,13 +6,13 @@ Versions and Releases | Ransack documentation - +

Versions and Releases

Semantic Versioning

Ransack attempts to follow semantic versioning in the format of x.y.z, where:

x stands for a major version (new features that are not backward-compatible).

y stands for a minor version (new features that are backward-compatible).

z stands for a patch (bug fixes).

In other words: Major.Minor.Patch.

Release Process

For the maintainers of Ransack.

To release a new version of Ransack and publish it to RubyGems, take the following steps:

  • Create a new release, marked Prerelease.
  • Update the versions file to the new release, commit and push to master.
  • Update the version.rb file to the new release, commit and push to master.
  • From the terminal, run the following commands:
rake build
rake release

Create a Release

- + \ No newline at end of file diff --git a/going-further/saving-queries.html b/going-further/saving-queries.html index 2561754..7f7a0a1 100644 --- a/going-further/saving-queries.html +++ b/going-further/saving-queries.html @@ -6,13 +6,13 @@ Saving queries | Ransack documentation - +

Saving queries

Ransack Memory Gem

The Ransack Memory gem accomplishes this.

Custom solution

If you want a custom solution, you can build it yourself. My ransack AJAX searching doesn’t save your search parameters across transactions. In this post I’ll show you how to easily add this capability in a generic way.

In this example I added AJAX search ability to index pages.

def index
@search = ComponentDefinition.search(search_params)
# make name the default sort column
@search.sorts = 'name' if @search.sorts.empty?
@component_definitions = @search.result().page(params[:page])
end

I added methods(search_params, clear_search_index) in the ApplicationController to add a level of abstraction from the search gem I was using. Turns out this made things super easy, especially considering I won’t have to update my code generation tools for index pages.

class ApplicationController < ActionController::Base
def search_params
params[:q]
end
def clear_search_index
if params[:search_cancel]
params.delete(:search_cancel)
if(!search_params.nil?)
search_params.each do |key, param|
search_params[key] = nil
end
end
end
end
end

I decided to store the ransack search parameters, params[:q], in the session. To make the session parameter unique I used a key creed from the controllers name and “_search”.

class ApplicationController < ActionController::Base

# CHECK THE SESSION FOR SEARCH PARAMETERS IS THEY AREN'T IN THE REQUEST
def search_params
if params[:q] == nil
params[:q] = session[search_key]
end
if params[:q]
session[search_key] = params[:q]
end
params[:q]
end
# DELETE SEARCH PARAMETERS FROM THE SESSION
def clear_search_index
if params[:search_cancel]
params.delete(:search_cancel)
if(!search_params.nil?)
search_params.each do |key, param|
search_params[key] = nil
end
end
# REMOVE FROM SESSION
session.delete(search_key)
end
end

protected
# GENERATE A GENERIC SESSION KEY BASED ON TEH CONTROLLER NAME
def search_key
"#{controller_name}_search".to_sym
end
end

Based on Saving queries

- + \ No newline at end of file diff --git a/going-further/searching-postgres.html b/going-further/searching-postgres.html index 11d731a..2aa1e53 100644 --- a/going-further/searching-postgres.html +++ b/going-further/searching-postgres.html @@ -6,13 +6,13 @@ Postgres searches | Ransack documentation - +

Postgres searches

Searching on Postgres-specific column types.

Postgres Array searches

See this issue for details.

PostgreSQL JSONB searches

Using a fixed key

See here for searching on a fixed key in a JSONB column: https://github.com/activerecord-hackery/ransack/wiki/Using-Ransackers#3-search-on-a-fixed-key-in-a-jsonb--hstore-column

Using the JSONB contains operator

To fully use the power of the JSONB column you may want to filter on any key though:

Install the ActiveRecordExtended gem to add the contains arel predicate to your project. It let's you use the Postgres contains operator @>.

Add a custom predicate in the config/initializers/ransack.rb file:

Ransack.configure do |config|
config.add_predicate 'jcont', arel_predicate: 'contains', formatter: proc { |v| JSON.parse(v) }
end

Now you can ransack the JSONB columns using the _jcont predicate. For example the Person model has a data JSONB column, find entries where the column contains the {"group": "experts"} key-value pair:

Person.ransack(data_jcont: '{"group": "experts"}').result.to_sql

SELECT "persons".* FROM "persons" WHERE "persons"."data" @> '"{\"group\": \"experts\"}"'

If you have a GIN index on that column, the database will quickly be able to find that result.

Treating the column as a string

Warning: This method converts the column to a string and matches the given string to the result. This will be slow on large data_sets and does not make good use of the JSONB capabilities of Postgres, such as indexes.

class Contact < ApplicationRecord
ransacker :within_json do |parent|
Arel.sql("table.jsonb_data::text")
end
end

Contact.all.ransack("within_json_cont" => "my")

Will generate

SELECT "contacts".* FROM "contacts" WHERE contacts.json_data ILIKE '%my%'

Note that this search treats the entire JSON as string, including parens, etc. i.e. you can search for e.g.: Contact.all.ransack("within_json_cont" => '{"key": "value"}')

- + \ No newline at end of file diff --git a/index.html b/index.html index 71b24c9..8fefc1b 100644 --- a/index.html +++ b/index.html @@ -6,7 +6,7 @@ Introduction | Ransack documentation - + @@ -19,7 +19,7 @@ request with passing tests is even better!
  • Before filing an issue or pul directly related to bug reports, pull requests, or documentation improvements.
  • Spread the word on Twitter, Facebook, and elsewhere if Ransack's been useful to you. The more people who are using the project, the quicker we can find and fix bugs!
  • Contributors

    Ransack was created by Ernie Miller and is developed and maintained by:

    Alumni Maintainers

    This project exists thanks to all the people who contribute.

    Backers

    Thank you to all our backers! 🙏 [Become a backer]

    Sponsors

    Support this project by becoming a sponsor. Your logo will show up here with a link to your website. [Become a sponsor]

    - + \ No newline at end of file diff --git a/markdown-page.html b/markdown-page.html index edd67a8..62ab40d 100644 --- a/markdown-page.html +++ b/markdown-page.html @@ -6,13 +6,13 @@ Markdown page example | Ransack documentation - +

    Markdown page example

    You don't need React to write simple standalone pages.

    - + \ No newline at end of file