diff --git a/404.html b/404.html index 3f67b92..98f0c5a 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/bb5657b1.9e963502.js b/assets/js/bb5657b1.9e963502.js new file mode 100644 index 0000000..884bca0 --- /dev/null +++ b/assets/js/bb5657b1.9e963502.js @@ -0,0 +1 @@ +"use strict";(self.webpackChunkdocs_website=self.webpackChunkdocs_website||[]).push([[8197],{3905:function(e,t,n){n.d(t,{Zo:function(){return p},kt:function(){return m}});var a=n(7294);function r(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function s(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var a=Object.getOwnPropertySymbols(e);t&&(a=a.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),n.push.apply(n,a)}return n}function l(e){for(var t=1;t=0||(r[n]=e[n]);return r}(e,t);if(Object.getOwnPropertySymbols){var s=Object.getOwnPropertySymbols(e);for(a=0;a=0||Object.prototype.propertyIsEnumerable.call(e,n)&&(r[n]=e[n])}return r}var o=a.createContext({}),u=function(e){var t=a.useContext(o),n=t;return e&&(n="function"==typeof e?e(t):l(l({},t),e)),n},p=function(e){var t=u(e.components);return a.createElement(o.Provider,{value:t},e.children)},c={inlineCode:"code",wrapper:function(e){var t=e.children;return a.createElement(a.Fragment,{},t)}},d=a.forwardRef((function(e,t){var n=e.components,r=e.mdxType,s=e.originalType,o=e.parentName,p=i(e,["components","mdxType","originalType","parentName"]),d=u(n),m=r,k=d["".concat(o,".").concat(m)]||d[m]||c[m]||s;return n?a.createElement(k,l(l({ref:t},p),{},{components:n})):a.createElement(k,l({ref:t},p))}));function m(e,t){var n=arguments,r=t&&t.mdxType;if("string"==typeof e||r){var s=n.length,l=new Array(s);l[0]=d;var i={};for(var o in t)hasOwnProperty.call(t,o)&&(i[o]=t[o]);i.originalType=e,i.mdxType="string"==typeof e?e:r,l[1]=i;for(var u=2;u> User.ransack(first_name_cont: \'Rya\').result.to_sql\n=> SELECT "users".* FROM "users" WHERE ("users"."first_name" LIKE \'%Rya%\')\n')),(0,s.kt)("p",null,"You can also combine predicates for OR queries:"),(0,s.kt)("pre",null,(0,s.kt)("code",{parentName:"pre",className:"language-ruby"},'>> User.ransack(first_name_or_last_name_cont: \'Rya\').result.to_sql\n=> SELECT "users".* FROM "users" WHERE ("users"."first_name" LIKE \'%Rya%\'\n OR "users"."last_name" LIKE \'%Rya%\')\n')),(0,s.kt)("p",null,"The syntax for ",(0,s.kt)("inlineCode",{parentName:"p"},"OR")," queries on an associated model is not immediately obvious, but makes sense. Assuming a ",(0,s.kt)("inlineCode",{parentName:"p"},"User")," ",(0,s.kt)("inlineCode",{parentName:"p"},"has_one")," ",(0,s.kt)("inlineCode",{parentName:"p"},"Account")," and the ",(0,s.kt)("inlineCode",{parentName:"p"},"Account")," has ",(0,s.kt)("inlineCode",{parentName:"p"},"attributes")," ",(0,s.kt)("inlineCode",{parentName:"p"},"foo")," and ",(0,s.kt)("inlineCode",{parentName:"p"},"bar"),":"),(0,s.kt)("pre",null,(0,s.kt)("code",{parentName:"pre",className:"language-ruby"},">> User.ransack(account_foo_or_account_bar_cont: 'val').result.to_sql\n=> SELECT \"users\".* FROM \"users\" INNER JOIN accounts ON accounts.user_id = users.id WHERE (\"accounts.foo LIKE '%val%' OR accounts.bar LIKE '%val%')\n")),(0,s.kt)("p",null,"Below is a list of the built-in predicates of Ransack and their opposites. You may already\nbe familiar with some of the predicates, as they also exist in the ARel library."),(0,s.kt)("p",null,"If you want to add your own, please\nsee the [","[Custom-Predicates|Custom Predicates]","] page."),(0,s.kt)("p",null,(0,s.kt)("strong",{parentName:"p"},"Please note:")," any attempt to use a predicate for an attribute that does not exist will\n",(0,s.kt)("em",{parentName:"p"},"silently fail"),". For instance, this will not work when there is no ",(0,s.kt)("inlineCode",{parentName:"p"},"name")," attribute:"),(0,s.kt)("pre",null,(0,s.kt)("code",{parentName:"pre",className:"language-ruby"},'>> User.ransack(name_cont: \'Rya\').result.to_sql\n=> "SELECT "users".* FROM "users"\n')),(0,s.kt)("h2",{id:"eq-equals"},"eq (equals)"),(0,s.kt)("p",null,"The ",(0,s.kt)("inlineCode",{parentName:"p"},"eq")," predicate returns all records where a field is ",(0,s.kt)("em",{parentName:"p"},"exactly")," equal to a given value:"),(0,s.kt)("pre",null,(0,s.kt)("code",{parentName:"pre",className:"language-ruby"},'>> User.ransack(first_name_eq: \'Ryan\').result.to_sql\n=> SELECT "users".* FROM "users" WHERE "users"."first_name" = \'Ryan\'\n')),(0,s.kt)("p",null,(0,s.kt)("strong",{parentName:"p"},"Opposite: ",(0,s.kt)("inlineCode",{parentName:"strong"},"not_eq"))),(0,s.kt)("h2",{id:"matches"},"matches"),(0,s.kt)("p",null,"The ",(0,s.kt)("inlineCode",{parentName:"p"},"matches")," predicate returns all records where a field is like a given value:"),(0,s.kt)("pre",null,(0,s.kt)("code",{parentName:"pre",className:"language-ruby"},'>> User.ransack(first_name_matches: \'Ryan\').result.to_sql\n=> SELECT "users".* FROM "users" WHERE ("users"."first_name" LIKE \'Ryan\')\n')),(0,s.kt)("p",null,"On Postgres, the case-insensitive ILIKE will be used."),(0,s.kt)("p",null,(0,s.kt)("strong",{parentName:"p"},"Opposite: ",(0,s.kt)("inlineCode",{parentName:"strong"},"does_not_match"))),(0,s.kt)("p",null,(0,s.kt)("em",{parentName:"p"},"Note: If you want to do wildcard matching, you may be looking for the ",(0,s.kt)("inlineCode",{parentName:"em"},"cont"),"/",(0,s.kt)("inlineCode",{parentName:"em"},"not_cont"),"\npredicates instead.")),(0,s.kt)("h2",{id:"lt-less-than"},"lt (less than)"),(0,s.kt)("p",null,"The ",(0,s.kt)("inlineCode",{parentName:"p"},"lt")," predicate returns all records where a field is less than a given value:"),(0,s.kt)("pre",null,(0,s.kt)("code",{parentName:"pre",className:"language-ruby"},'>> User.ransack(age_lt: 25).result.to_sql\n=> SELECT "users".* FROM "users" WHERE ("users"."age" < 25)\n')),(0,s.kt)("p",null,(0,s.kt)("strong",{parentName:"p"},"Opposite: ",(0,s.kt)("inlineCode",{parentName:"strong"},"gteq")," (greater than or equal to)")),(0,s.kt)("h2",{id:"lteq-less-than-or-equal-to"},"lteq (less than or equal to)"),(0,s.kt)("p",null,"The ",(0,s.kt)("inlineCode",{parentName:"p"},"lteq")," predicate returns all records where a field is less than ",(0,s.kt)("em",{parentName:"p"},"or equal to")," a given value:"),(0,s.kt)("pre",null,(0,s.kt)("code",{parentName:"pre",className:"language-ruby"},'>> User.ransack(age_lteq: 25).result.to_sql\n=> SELECT "users".* FROM "users" WHERE ("users"."age" <= 25)\n')),(0,s.kt)("p",null,(0,s.kt)("strong",{parentName:"p"},"Opposite: ",(0,s.kt)("inlineCode",{parentName:"strong"},"gt")," (greater than)")),(0,s.kt)("h2",{id:"in"},"in"),(0,s.kt)("p",null,"The ",(0,s.kt)("inlineCode",{parentName:"p"},"in")," predicate returns all records where a field is within a specified list:"),(0,s.kt)("pre",null,(0,s.kt)("code",{parentName:"pre",className:"language-ruby"},'>> User.ransack(age_in: 20..25).result.to_sql\n=> SELECT "users".* FROM "users" WHERE "users"."age" IN (20, 21, 22, 23, 24, 25)\n')),(0,s.kt)("p",null,"It can also take an array:"),(0,s.kt)("pre",null,(0,s.kt)("code",{parentName:"pre",className:"language-ruby"},'>> User.ransack(age_in: [20, 21, 22, 23, 24, 25]).result.to_sql\n=> SELECT "users".* FROM "users" WHERE "users"."age" IN (20, 21, 22, 23, 24, 25)\n')),(0,s.kt)("p",null,(0,s.kt)("strong",{parentName:"p"},"Opposite: ",(0,s.kt)("inlineCode",{parentName:"strong"},"not_in"))),(0,s.kt)("h2",{id:"cont"},"cont"),(0,s.kt)("p",null,"The ",(0,s.kt)("inlineCode",{parentName:"p"},"cont")," predicate returns all records where a field contains a given value:"),(0,s.kt)("pre",null,(0,s.kt)("code",{parentName:"pre",className:"language-ruby"},'>> User.ransack(first_name_cont: \'Rya\').result.to_sql\n=> SELECT "users".* FROM "users" WHERE ("users"."first_name" LIKE \'%Rya%\')\n')),(0,s.kt)("p",null,(0,s.kt)("strong",{parentName:"p"},"Opposite: ",(0,s.kt)("inlineCode",{parentName:"strong"},"not_cont"))),(0,s.kt)("h2",{id:"cont_any-contains-any"},"cont_any (contains any)"),(0,s.kt)("p",null,"The ",(0,s.kt)("inlineCode",{parentName:"p"},"cont_any")," predicate returns all records where a field contains any of the given values:"),(0,s.kt)("pre",null,(0,s.kt)("code",{parentName:"pre",className:"language-ruby"},'>> User.ransack(first_name_cont_any: %w(Rya Lis)).result.to_sql\n=> SELECT "users".* FROM "users" WHERE (("users"."first_name" LIKE \'%Rya%\' OR "users"."first_name" LIKE \'%Lis%\'))\n')),(0,s.kt)("p",null,(0,s.kt)("strong",{parentName:"p"},"Opposite: ",(0,s.kt)("inlineCode",{parentName:"strong"},"not_cont_any"))),(0,s.kt)("h2",{id:"cont_all-contains-all"},"cont_all (contains all)"),(0,s.kt)("p",null,"The ",(0,s.kt)("inlineCode",{parentName:"p"},"cont_all")," predicate returns all records where a field contains all of the given values:"),(0,s.kt)("pre",null,(0,s.kt)("code",{parentName:"pre",className:"language-ruby"},'>> User.ransack(city_cont_all: %w(Grand Rapids)).result.to_sql\n=> SELECT "users".* FROM "users" WHERE (("users"."city" LIKE \'%Grand%\' AND "users"."city" LIKE \'%Rapids%\'))\n')),(0,s.kt)("p",null,(0,s.kt)("strong",{parentName:"p"},"Opposite: ",(0,s.kt)("inlineCode",{parentName:"strong"},"not_cont_all"))),(0,s.kt)("h2",{id:"i_cont"},"i_cont"),(0,s.kt)("p",null,"The ",(0,s.kt)("inlineCode",{parentName:"p"},"i_cont")," case-insensitive predicate returns all records where a field contains a given value and ignores case:"),(0,s.kt)("pre",null,(0,s.kt)("code",{parentName:"pre",className:"language-ruby"},'>> User.ransack(first_name_i_cont: \'Rya\').result.to_sql\n=> SELECT "users".* FROM "users" WHERE (LOWER("users"."first_name") LIKE \'%rya%\')\n')),(0,s.kt)("p",null,(0,s.kt)("strong",{parentName:"p"},"Opposite: ",(0,s.kt)("inlineCode",{parentName:"strong"},"not_i_cont"))),(0,s.kt)("h2",{id:"i_cont_any"},"i_cont_any"),(0,s.kt)("p",null,"The ",(0,s.kt)("inlineCode",{parentName:"p"},"i_cont_any")," case-insensitive predicate returns all records where a field contains any of the given values and ignores case:"),(0,s.kt)("pre",null,(0,s.kt)("code",{parentName:"pre",className:"language-ruby"},'>> User.ransack(first_name_i_cont_any: %w(Rya Lis)).result.to_sql\n=> SELECT "users".* FROM "users" WHERE ((LOWER("users"."first_name") LIKE \'%rya%\' OR LOWER("users"."first_name") LIKE \'%lis%\'))\n')),(0,s.kt)("p",null,(0,s.kt)("strong",{parentName:"p"},"Opposite: ",(0,s.kt)("inlineCode",{parentName:"strong"},"not_i_cont_any"))),(0,s.kt)("h2",{id:"i_cont_all"},"i_cont_all"),(0,s.kt)("p",null,"The ",(0,s.kt)("inlineCode",{parentName:"p"},"i_cont_all")," case-insensitive predicate returns all records where a field contains all of the given values and ignores case:"),(0,s.kt)("pre",null,(0,s.kt)("code",{parentName:"pre",className:"language-ruby"},'>> User.ransack(city_i_cont_all: %w(Grand Rapids)).result.to_sql\n=> SELECT "users".* FROM "users" WHERE ((LOWER("users"."city") LIKE \'%grand%\' AND LOWER("users"."city") LIKE \'%rapids%\'))\n')),(0,s.kt)("p",null,(0,s.kt)("strong",{parentName:"p"},"Opposite: ",(0,s.kt)("inlineCode",{parentName:"strong"},"not_i_cont_all"))),(0,s.kt)("h2",{id:"start-starts-with"},"start (starts with)"),(0,s.kt)("p",null,"The ",(0,s.kt)("inlineCode",{parentName:"p"},"start")," predicate returns all records where a field begins with a given value:"),(0,s.kt)("pre",null,(0,s.kt)("code",{parentName:"pre",className:"language-ruby"},'>> User.ransack(first_name_start: \'Rya\').result.to_sql\n=> SELECT "users".* FROM "users" WHERE ("users"."first_name" LIKE \'Rya%\')\n')),(0,s.kt)("p",null,(0,s.kt)("strong",{parentName:"p"},"Opposite: ",(0,s.kt)("inlineCode",{parentName:"strong"},"not_start"))),(0,s.kt)("h2",{id:"end-ends-with"},"end (ends with)"),(0,s.kt)("p",null,"The ",(0,s.kt)("inlineCode",{parentName:"p"},"end")," predicate returns all records where a field ends with a given value:"),(0,s.kt)("pre",null,(0,s.kt)("code",{parentName:"pre",className:"language-ruby"},'>> User.ransack(first_name_end: \'yan\').result.to_sql\n=> SELECT "users".* FROM "users" WHERE ("users"."first_name" LIKE \'%yan\')\n')),(0,s.kt)("p",null,(0,s.kt)("strong",{parentName:"p"},"Opposite: ",(0,s.kt)("inlineCode",{parentName:"strong"},"not_end"))),(0,s.kt)("h2",{id:"true"},"true"),(0,s.kt)("p",null,"The ",(0,s.kt)("inlineCode",{parentName:"p"},"true")," predicate returns all records where a field is true. The '1' indicates that\nto Ransack that you indeed want to check the truthiness of this field. The other truthy\nvalues are 'true', 'TRUE', 't' or 'T'."),(0,s.kt)("pre",null,(0,s.kt)("code",{parentName:"pre",className:"language-ruby"},'>> User.ransack(awesome_true: \'1\').result.to_sql\n=> SELECT "users".* FROM "users" WHERE ("users"."awesome" = \'t\')\n')),(0,s.kt)("p",null,(0,s.kt)("em",{parentName:"p"},"Note: different database systems use different values to represent truth. In the above\nexample, we are using SQLite3.")),(0,s.kt)("p",null,(0,s.kt)("strong",{parentName:"p"},"Opposite: ",(0,s.kt)("inlineCode",{parentName:"strong"},"not_true"))),(0,s.kt)("h2",{id:"false"},"false"),(0,s.kt)("p",null,"The ",(0,s.kt)("inlineCode",{parentName:"p"},"false")," predicate returns all records where a field is false."),(0,s.kt)("pre",null,(0,s.kt)("code",{parentName:"pre",className:"language-ruby"},'>> User.ransack(awesome_false: \'1\').result.to_sql\n=> SELECT "users".* FROM "users" WHERE ("users"."awesome" = \'f\')\n')),(0,s.kt)("p",null,(0,s.kt)("strong",{parentName:"p"},"Opposite: ",(0,s.kt)("inlineCode",{parentName:"strong"},"not_false"))),(0,s.kt)("p",null,(0,s.kt)("em",{parentName:"p"},"Note: the ",(0,s.kt)("inlineCode",{parentName:"em"},"false")," predicate may be considered the opposite of the ",(0,s.kt)("inlineCode",{parentName:"em"},"true")," predicate if the field does not contain ",(0,s.kt)("inlineCode",{parentName:"em"},"null")," values. Otherwise, use ",(0,s.kt)("inlineCode",{parentName:"em"},"not_false"),".")),(0,s.kt)("h2",{id:"present"},"present"),(0,s.kt)("p",null,"The ",(0,s.kt)("inlineCode",{parentName:"p"},"present")," predicate returns all records where a field is present (not null and not a\nblank string)."),(0,s.kt)("pre",null,(0,s.kt)("code",{parentName:"pre",className:"language-ruby"},'>> User.ransack(first_name_present: \'1\').result.to_sql\n=> SELECT "users".* FROM "users" WHERE (("users"."first_name" IS NOT NULL AND "users"."first_name" != \'\'))\n')),(0,s.kt)("p",null,(0,s.kt)("strong",{parentName:"p"},"Opposite: ",(0,s.kt)("inlineCode",{parentName:"strong"},"blank"))),(0,s.kt)("h2",{id:"null"},"null"),(0,s.kt)("p",null,"The ",(0,s.kt)("inlineCode",{parentName:"p"},"null")," predicate returns all records where a field is null:"),(0,s.kt)("pre",null,(0,s.kt)("code",{parentName:"pre",className:"language-ruby"},'>> User.ransack(first_name_null: 1).result.to_sql\n=> SELECT "users".* FROM "users" WHERE "users"."first_name" IS NULL\n')),(0,s.kt)("p",null,(0,s.kt)("strong",{parentName:"p"},"Opposite: ",(0,s.kt)("inlineCode",{parentName:"strong"},"not_null"))),(0,s.kt)("h1",{id:"url-parameter-structure"},"URL parameter structure"),(0,s.kt)("p",null,"The search parameters are passed to ransack as a hash. The URL representation of this hash uses the bracket notation: ",(0,s.kt)("inlineCode",{parentName:"p"},"hash_name[key]=value"),". The hash_name is the parameter which is defined in the controller, for instance ",(0,s.kt)("inlineCode",{parentName:"p"},"q"),". The key is the attribute and search predicate compound, for instance ",(0,s.kt)("inlineCode",{parentName:"p"},"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."),(0,s.kt)("p",null,"For example, the URL layout for searching and sorting users could looks like this:"),(0,s.kt)("pre",null,(0,s.kt)("code",{parentName:"pre"},"/users.json?q[first_name_cont]=pete&q[last_name_cont]=jack&q[s]=created_at+desc\n")),(0,s.kt)("p",null,(0,s.kt)("em",{parentName:"p"},"Note that the sorting parameter ",(0,s.kt)("inlineCode",{parentName:"em"},"s")," is nested within the ",(0,s.kt)("inlineCode",{parentName:"em"},"q")," hash.")),(0,s.kt)("p",null,"When using JavaScript to create such a URL, a matching jQuery request could look like this:"),(0,s.kt)("pre",null,(0,s.kt)("code",{parentName:"pre",className:"language-javascript"},'$.ajax({\n url: "/users.json",\n data: {\n q: {\n first_name_cont: "pete",\n last_name_cont: "jack",\n s: "created_at desc"\n }\n },\n success: function (data){\n console.log(data);\n }\n});\n')))}m.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/bb5657b1.ca6adc84.js b/assets/js/bb5657b1.ca6adc84.js deleted file mode 100644 index 2236052..0000000 --- a/assets/js/bb5657b1.ca6adc84.js +++ /dev/null @@ -1 +0,0 @@ -"use strict";(self.webpackChunkdocs_website=self.webpackChunkdocs_website||[]).push([[8197],{3905:function(e,t,n){n.d(t,{Zo:function(){return p},kt:function(){return m}});var a=n(7294);function r(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function s(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var a=Object.getOwnPropertySymbols(e);t&&(a=a.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),n.push.apply(n,a)}return n}function l(e){for(var t=1;t=0||(r[n]=e[n]);return r}(e,t);if(Object.getOwnPropertySymbols){var s=Object.getOwnPropertySymbols(e);for(a=0;a=0||Object.prototype.propertyIsEnumerable.call(e,n)&&(r[n]=e[n])}return r}var o=a.createContext({}),u=function(e){var t=a.useContext(o),n=t;return e&&(n="function"==typeof e?e(t):l(l({},t),e)),n},p=function(e){var t=u(e.components);return a.createElement(o.Provider,{value:t},e.children)},c={inlineCode:"code",wrapper:function(e){var t=e.children;return a.createElement(a.Fragment,{},t)}},d=a.forwardRef((function(e,t){var n=e.components,r=e.mdxType,s=e.originalType,o=e.parentName,p=i(e,["components","mdxType","originalType","parentName"]),d=u(n),m=r,k=d["".concat(o,".").concat(m)]||d[m]||c[m]||s;return n?a.createElement(k,l(l({ref:t},p),{},{components:n})):a.createElement(k,l({ref:t},p))}));function m(e,t){var n=arguments,r=t&&t.mdxType;if("string"==typeof e||r){var s=n.length,l=new Array(s);l[0]=d;var i={};for(var o in t)hasOwnProperty.call(t,o)&&(i[o]=t[o]);i.originalType=e,i.mdxType="string"==typeof e?e:r,l[1]=i;for(var u=2;u> User.ransack(first_name_cont: \'Rya\').result.to_sql\n=> SELECT "users".* FROM "users" WHERE ("users"."first_name" LIKE \'%Rya%\')\n')),(0,s.kt)("p",null,"You can also combine predicates for OR queries:"),(0,s.kt)("pre",null,(0,s.kt)("code",{parentName:"pre",className:"language-ruby"},'>> User.ransack(first_name_or_last_name_cont: \'Rya\').result.to_sql\n=> SELECT "users".* FROM "users" WHERE ("users"."first_name" LIKE \'%Rya%\'\n OR "users"."last_name" LIKE \'%Rya%\')\n')),(0,s.kt)("p",null,"The syntax for ",(0,s.kt)("inlineCode",{parentName:"p"},"OR")," queries on an associated model is not immediately obvious, but makes sense. Assuming a ",(0,s.kt)("inlineCode",{parentName:"p"},"User")," ",(0,s.kt)("inlineCode",{parentName:"p"},"has_one")," ",(0,s.kt)("inlineCode",{parentName:"p"},"Account")," and the ",(0,s.kt)("inlineCode",{parentName:"p"},"Account")," has ",(0,s.kt)("inlineCode",{parentName:"p"},"attributes")," ",(0,s.kt)("inlineCode",{parentName:"p"},"foo")," and ",(0,s.kt)("inlineCode",{parentName:"p"},"bar"),":"),(0,s.kt)("pre",null,(0,s.kt)("code",{parentName:"pre",className:"language-ruby"},">> User.ransack(account_foo_or_account_bar: 'val').result.to_sql\n=> SELECT \"users\".* FROM \"users\" INNER JOIN accounts ON accounts.user_id = users.id WHERE (\"accounts.foo LIKE '%val%' OR accounts.bar LIKE '%val%')\n")),(0,s.kt)("p",null,"Below is a list of the built-in predicates of Ransack and their opposites. You may already\nbe familiar with some of the predicates, as they also exist in the ARel library."),(0,s.kt)("p",null,"If you want to add your own, please\nsee the [","[Custom-Predicates|Custom Predicates]","] page."),(0,s.kt)("p",null,(0,s.kt)("strong",{parentName:"p"},"Please note:")," any attempt to use a predicate for an attribute that does not exist will\n",(0,s.kt)("em",{parentName:"p"},"silently fail"),". For instance, this will not work when there is no ",(0,s.kt)("inlineCode",{parentName:"p"},"name")," attribute:"),(0,s.kt)("pre",null,(0,s.kt)("code",{parentName:"pre",className:"language-ruby"},'>> User.ransack(name_cont: \'Rya\').result.to_sql\n=> "SELECT "users".* FROM "users"\n')),(0,s.kt)("h2",{id:"eq-equals"},"eq (equals)"),(0,s.kt)("p",null,"The ",(0,s.kt)("inlineCode",{parentName:"p"},"eq")," predicate returns all records where a field is ",(0,s.kt)("em",{parentName:"p"},"exactly")," equal to a given value:"),(0,s.kt)("pre",null,(0,s.kt)("code",{parentName:"pre",className:"language-ruby"},'>> User.ransack(first_name_eq: \'Ryan\').result.to_sql\n=> SELECT "users".* FROM "users" WHERE "users"."first_name" = \'Ryan\'\n')),(0,s.kt)("p",null,(0,s.kt)("strong",{parentName:"p"},"Opposite: ",(0,s.kt)("inlineCode",{parentName:"strong"},"not_eq"))),(0,s.kt)("h2",{id:"matches"},"matches"),(0,s.kt)("p",null,"The ",(0,s.kt)("inlineCode",{parentName:"p"},"matches")," predicate returns all records where a field is like a given value:"),(0,s.kt)("pre",null,(0,s.kt)("code",{parentName:"pre",className:"language-ruby"},'>> User.ransack(first_name_matches: \'Ryan\').result.to_sql\n=> SELECT "users".* FROM "users" WHERE ("users"."first_name" LIKE \'Ryan\')\n')),(0,s.kt)("p",null,"On Postgres, the case-insensitive ILIKE will be used."),(0,s.kt)("p",null,(0,s.kt)("strong",{parentName:"p"},"Opposite: ",(0,s.kt)("inlineCode",{parentName:"strong"},"does_not_match"))),(0,s.kt)("p",null,(0,s.kt)("em",{parentName:"p"},"Note: If you want to do wildcard matching, you may be looking for the ",(0,s.kt)("inlineCode",{parentName:"em"},"cont"),"/",(0,s.kt)("inlineCode",{parentName:"em"},"not_cont"),"\npredicates instead.")),(0,s.kt)("h2",{id:"lt-less-than"},"lt (less than)"),(0,s.kt)("p",null,"The ",(0,s.kt)("inlineCode",{parentName:"p"},"lt")," predicate returns all records where a field is less than a given value:"),(0,s.kt)("pre",null,(0,s.kt)("code",{parentName:"pre",className:"language-ruby"},'>> User.ransack(age_lt: 25).result.to_sql\n=> SELECT "users".* FROM "users" WHERE ("users"."age" < 25)\n')),(0,s.kt)("p",null,(0,s.kt)("strong",{parentName:"p"},"Opposite: ",(0,s.kt)("inlineCode",{parentName:"strong"},"gteq")," (greater than or equal to)")),(0,s.kt)("h2",{id:"lteq-less-than-or-equal-to"},"lteq (less than or equal to)"),(0,s.kt)("p",null,"The ",(0,s.kt)("inlineCode",{parentName:"p"},"lteq")," predicate returns all records where a field is less than ",(0,s.kt)("em",{parentName:"p"},"or equal to")," a given value:"),(0,s.kt)("pre",null,(0,s.kt)("code",{parentName:"pre",className:"language-ruby"},'>> User.ransack(age_lteq: 25).result.to_sql\n=> SELECT "users".* FROM "users" WHERE ("users"."age" <= 25)\n')),(0,s.kt)("p",null,(0,s.kt)("strong",{parentName:"p"},"Opposite: ",(0,s.kt)("inlineCode",{parentName:"strong"},"gt")," (greater than)")),(0,s.kt)("h2",{id:"in"},"in"),(0,s.kt)("p",null,"The ",(0,s.kt)("inlineCode",{parentName:"p"},"in")," predicate returns all records where a field is within a specified list:"),(0,s.kt)("pre",null,(0,s.kt)("code",{parentName:"pre",className:"language-ruby"},'>> User.ransack(age_in: 20..25).result.to_sql\n=> SELECT "users".* FROM "users" WHERE "users"."age" IN (20, 21, 22, 23, 24, 25)\n')),(0,s.kt)("p",null,"It can also take an array:"),(0,s.kt)("pre",null,(0,s.kt)("code",{parentName:"pre",className:"language-ruby"},'>> User.ransack(age_in: [20, 21, 22, 23, 24, 25]).result.to_sql\n=> SELECT "users".* FROM "users" WHERE "users"."age" IN (20, 21, 22, 23, 24, 25)\n')),(0,s.kt)("p",null,(0,s.kt)("strong",{parentName:"p"},"Opposite: ",(0,s.kt)("inlineCode",{parentName:"strong"},"not_in"))),(0,s.kt)("h2",{id:"cont"},"cont"),(0,s.kt)("p",null,"The ",(0,s.kt)("inlineCode",{parentName:"p"},"cont")," predicate returns all records where a field contains a given value:"),(0,s.kt)("pre",null,(0,s.kt)("code",{parentName:"pre",className:"language-ruby"},'>> User.ransack(first_name_cont: \'Rya\').result.to_sql\n=> SELECT "users".* FROM "users" WHERE ("users"."first_name" LIKE \'%Rya%\')\n')),(0,s.kt)("p",null,(0,s.kt)("strong",{parentName:"p"},"Opposite: ",(0,s.kt)("inlineCode",{parentName:"strong"},"not_cont"))),(0,s.kt)("h2",{id:"cont_any-contains-any"},"cont_any (contains any)"),(0,s.kt)("p",null,"The ",(0,s.kt)("inlineCode",{parentName:"p"},"cont_any")," predicate returns all records where a field contains any of the given values:"),(0,s.kt)("pre",null,(0,s.kt)("code",{parentName:"pre",className:"language-ruby"},'>> User.ransack(first_name_cont_any: %w(Rya Lis)).result.to_sql\n=> SELECT "users".* FROM "users" WHERE (("users"."first_name" LIKE \'%Rya%\' OR "users"."first_name" LIKE \'%Lis%\'))\n')),(0,s.kt)("p",null,(0,s.kt)("strong",{parentName:"p"},"Opposite: ",(0,s.kt)("inlineCode",{parentName:"strong"},"not_cont_any"))),(0,s.kt)("h2",{id:"cont_all-contains-all"},"cont_all (contains all)"),(0,s.kt)("p",null,"The ",(0,s.kt)("inlineCode",{parentName:"p"},"cont_all")," predicate returns all records where a field contains all of the given values:"),(0,s.kt)("pre",null,(0,s.kt)("code",{parentName:"pre",className:"language-ruby"},'>> User.ransack(city_cont_all: %w(Grand Rapids)).result.to_sql\n=> SELECT "users".* FROM "users" WHERE (("users"."city" LIKE \'%Grand%\' AND "users"."city" LIKE \'%Rapids%\'))\n')),(0,s.kt)("p",null,(0,s.kt)("strong",{parentName:"p"},"Opposite: ",(0,s.kt)("inlineCode",{parentName:"strong"},"not_cont_all"))),(0,s.kt)("h2",{id:"i_cont"},"i_cont"),(0,s.kt)("p",null,"The ",(0,s.kt)("inlineCode",{parentName:"p"},"i_cont")," case-insensitive predicate returns all records where a field contains a given value and ignores case:"),(0,s.kt)("pre",null,(0,s.kt)("code",{parentName:"pre",className:"language-ruby"},'>> User.ransack(first_name_i_cont: \'Rya\').result.to_sql\n=> SELECT "users".* FROM "users" WHERE (LOWER("users"."first_name") LIKE \'%rya%\')\n')),(0,s.kt)("p",null,(0,s.kt)("strong",{parentName:"p"},"Opposite: ",(0,s.kt)("inlineCode",{parentName:"strong"},"not_i_cont"))),(0,s.kt)("h2",{id:"i_cont_any"},"i_cont_any"),(0,s.kt)("p",null,"The ",(0,s.kt)("inlineCode",{parentName:"p"},"i_cont_any")," case-insensitive predicate returns all records where a field contains any of the given values and ignores case:"),(0,s.kt)("pre",null,(0,s.kt)("code",{parentName:"pre",className:"language-ruby"},'>> User.ransack(first_name_i_cont_any: %w(Rya Lis)).result.to_sql\n=> SELECT "users".* FROM "users" WHERE ((LOWER("users"."first_name") LIKE \'%rya%\' OR LOWER("users"."first_name") LIKE \'%lis%\'))\n')),(0,s.kt)("p",null,(0,s.kt)("strong",{parentName:"p"},"Opposite: ",(0,s.kt)("inlineCode",{parentName:"strong"},"not_i_cont_any"))),(0,s.kt)("h2",{id:"i_cont_all"},"i_cont_all"),(0,s.kt)("p",null,"The ",(0,s.kt)("inlineCode",{parentName:"p"},"i_cont_all")," case-insensitive predicate returns all records where a field contains all of the given values and ignores case:"),(0,s.kt)("pre",null,(0,s.kt)("code",{parentName:"pre",className:"language-ruby"},'>> User.ransack(city_i_cont_all: %w(Grand Rapids)).result.to_sql\n=> SELECT "users".* FROM "users" WHERE ((LOWER("users"."city") LIKE \'%grand%\' AND LOWER("users"."city") LIKE \'%rapids%\'))\n')),(0,s.kt)("p",null,(0,s.kt)("strong",{parentName:"p"},"Opposite: ",(0,s.kt)("inlineCode",{parentName:"strong"},"not_i_cont_all"))),(0,s.kt)("h2",{id:"start-starts-with"},"start (starts with)"),(0,s.kt)("p",null,"The ",(0,s.kt)("inlineCode",{parentName:"p"},"start")," predicate returns all records where a field begins with a given value:"),(0,s.kt)("pre",null,(0,s.kt)("code",{parentName:"pre",className:"language-ruby"},'>> User.ransack(first_name_start: \'Rya\').result.to_sql\n=> SELECT "users".* FROM "users" WHERE ("users"."first_name" LIKE \'Rya%\')\n')),(0,s.kt)("p",null,(0,s.kt)("strong",{parentName:"p"},"Opposite: ",(0,s.kt)("inlineCode",{parentName:"strong"},"not_start"))),(0,s.kt)("h2",{id:"end-ends-with"},"end (ends with)"),(0,s.kt)("p",null,"The ",(0,s.kt)("inlineCode",{parentName:"p"},"end")," predicate returns all records where a field ends with a given value:"),(0,s.kt)("pre",null,(0,s.kt)("code",{parentName:"pre",className:"language-ruby"},'>> User.ransack(first_name_end: \'yan\').result.to_sql\n=> SELECT "users".* FROM "users" WHERE ("users"."first_name" LIKE \'%yan\')\n')),(0,s.kt)("p",null,(0,s.kt)("strong",{parentName:"p"},"Opposite: ",(0,s.kt)("inlineCode",{parentName:"strong"},"not_end"))),(0,s.kt)("h2",{id:"true"},"true"),(0,s.kt)("p",null,"The ",(0,s.kt)("inlineCode",{parentName:"p"},"true")," predicate returns all records where a field is true. The '1' indicates that\nto Ransack that you indeed want to check the truthiness of this field. The other truthy\nvalues are 'true', 'TRUE', 't' or 'T'."),(0,s.kt)("pre",null,(0,s.kt)("code",{parentName:"pre",className:"language-ruby"},'>> User.ransack(awesome_true: \'1\').result.to_sql\n=> SELECT "users".* FROM "users" WHERE ("users"."awesome" = \'t\')\n')),(0,s.kt)("p",null,(0,s.kt)("em",{parentName:"p"},"Note: different database systems use different values to represent truth. In the above\nexample, we are using SQLite3.")),(0,s.kt)("p",null,(0,s.kt)("strong",{parentName:"p"},"Opposite: ",(0,s.kt)("inlineCode",{parentName:"strong"},"not_true"))),(0,s.kt)("h2",{id:"false"},"false"),(0,s.kt)("p",null,"The ",(0,s.kt)("inlineCode",{parentName:"p"},"false")," predicate returns all records where a field is false."),(0,s.kt)("pre",null,(0,s.kt)("code",{parentName:"pre",className:"language-ruby"},'>> User.ransack(awesome_false: \'1\').result.to_sql\n=> SELECT "users".* FROM "users" WHERE ("users"."awesome" = \'f\')\n')),(0,s.kt)("p",null,(0,s.kt)("strong",{parentName:"p"},"Opposite: ",(0,s.kt)("inlineCode",{parentName:"strong"},"not_false"))),(0,s.kt)("p",null,(0,s.kt)("em",{parentName:"p"},"Note: the ",(0,s.kt)("inlineCode",{parentName:"em"},"false")," predicate may be considered the opposite of the ",(0,s.kt)("inlineCode",{parentName:"em"},"true")," predicate if the field does not contain ",(0,s.kt)("inlineCode",{parentName:"em"},"null")," values. Otherwise, use ",(0,s.kt)("inlineCode",{parentName:"em"},"not_false"),".")),(0,s.kt)("h2",{id:"present"},"present"),(0,s.kt)("p",null,"The ",(0,s.kt)("inlineCode",{parentName:"p"},"present")," predicate returns all records where a field is present (not null and not a\nblank string)."),(0,s.kt)("pre",null,(0,s.kt)("code",{parentName:"pre",className:"language-ruby"},'>> User.ransack(first_name_present: \'1\').result.to_sql\n=> SELECT "users".* FROM "users" WHERE (("users"."first_name" IS NOT NULL AND "users"."first_name" != \'\'))\n')),(0,s.kt)("p",null,(0,s.kt)("strong",{parentName:"p"},"Opposite: ",(0,s.kt)("inlineCode",{parentName:"strong"},"blank"))),(0,s.kt)("h2",{id:"null"},"null"),(0,s.kt)("p",null,"The ",(0,s.kt)("inlineCode",{parentName:"p"},"null")," predicate returns all records where a field is null:"),(0,s.kt)("pre",null,(0,s.kt)("code",{parentName:"pre",className:"language-ruby"},'>> User.ransack(first_name_null: 1).result.to_sql\n=> SELECT "users".* FROM "users" WHERE "users"."first_name" IS NULL\n')),(0,s.kt)("p",null,(0,s.kt)("strong",{parentName:"p"},"Opposite: ",(0,s.kt)("inlineCode",{parentName:"strong"},"not_null"))),(0,s.kt)("h1",{id:"url-parameter-structure"},"URL parameter structure"),(0,s.kt)("p",null,"The search parameters are passed to ransack as a hash. The URL representation of this hash uses the bracket notation: ",(0,s.kt)("inlineCode",{parentName:"p"},"hash_name[key]=value"),". The hash_name is the parameter which is defined in the controller, for instance ",(0,s.kt)("inlineCode",{parentName:"p"},"q"),". The key is the attribute and search predicate compound, for instance ",(0,s.kt)("inlineCode",{parentName:"p"},"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."),(0,s.kt)("p",null,"For example, the URL layout for searching and sorting users could looks like this:"),(0,s.kt)("pre",null,(0,s.kt)("code",{parentName:"pre"},"/users.json?q[first_name_cont]=pete&q[last_name_cont]=jack&q[s]=created_at+desc\n")),(0,s.kt)("p",null,(0,s.kt)("em",{parentName:"p"},"Note that the sorting parameter ",(0,s.kt)("inlineCode",{parentName:"em"},"s")," is nested within the ",(0,s.kt)("inlineCode",{parentName:"em"},"q")," hash.")),(0,s.kt)("p",null,"When using JavaScript to create such a URL, a matching jQuery request could look like this:"),(0,s.kt)("pre",null,(0,s.kt)("code",{parentName:"pre",className:"language-javascript"},'$.ajax({\n url: "/users.json",\n data: {\n q: {\n first_name_cont: "pete",\n last_name_cont: "jack",\n s: "created_at desc"\n }\n },\n success: function (data){\n console.log(data);\n }\n});\n')))}m.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/runtime~main.80d3242f.js b/assets/js/runtime~main.35280170.js similarity index 98% rename from assets/js/runtime~main.80d3242f.js rename to assets/js/runtime~main.35280170.js index 397595c..90acb0c 100644 --- a/assets/js/runtime~main.80d3242f.js +++ b/assets/js/runtime~main.35280170.js @@ -1 +1 @@ -!function(){"use strict";var e,t,n,r,f,c={},a={};function o(e){var t=a[e];if(void 0!==t)return t.exports;var n=a[e]={id:e,loaded:!1,exports:{}};return c[e].call(n.exports,n,n.exports,o),n.loaded=!0,n.exports}o.m=c,o.c=a,e=[],o.O=function(t,n,r,f){if(!n){var c=1/0;for(u=0;u=f)&&Object.keys(o.O).every((function(e){return o.O[e](n[b])}))?n.splice(b--,1):(a=!1,f0&&e[u-1][2]>f;u--)e[u]=e[u-1];e[u]=[n,r,f]},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,r){if(1&r&&(e=this(e)),8&r)return e;if("object"==typeof e&&e){if(4&r&&e.__esModule)return e;if(16&r&&"function"==typeof e.then)return e}var f=Object.create(null);o.r(f);var c={};t=t||[null,n({}),n([]),n(n)];for(var a=2&r&&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(f,c),f},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/"+({53:"935f2afb",189:"5647493f",230:"2bc2bb50",570:"31a91795",597:"db1f0725",722:"a6866e6d",1260:"b1e4a2bb",1628:"260cca1a",1719:"4eaee7fa",1782:"460f2046",1944:"99efcd31",1977:"3428807b",2168:"dffbd312",2364:"8c747907",2491:"9fa839ec",2535:"814f3328",2591:"92fe0e90",3015:"eae51d00",3085:"1f391b9e",3089:"a6aa9e1f",3245:"0d4fa94e",3436:"009f1e98",3608:"9e4087bc",3699:"ce7a2be6",3939:"01befa62",4013:"01a85c17",4510:"b8ab82ee",4841:"3fbeb73f",5395:"764f00df",5474:"fc57f22d",5600:"9c504410",6103:"ccc49370",6401:"52275109",6680:"a6235bd5",6843:"e3caf117",7324:"29104dc6",7341:"da250cee",7407:"7bf2db17",7414:"393be207",7918:"17896441",8197:"bb5657b1",8382:"7bc87c9b",8610:"6875c492",9514:"1be78505",9671:"0e384e19",9953:"d4672cd7"}[e]||e)+"."+{53:"47d31997",189:"a947a5ec",230:"cd54028c",570:"503f461d",597:"0cfae94d",722:"31993d98",1260:"b0d3c2b0",1628:"9230c8ff",1719:"b148bac1",1782:"b4f2df60",1944:"e061b5d4",1977:"d8b6adc0",2168:"5b363afd",2364:"9f52e60b",2491:"75f3450c",2535:"936543ce",2591:"080b1dba",3015:"13dd90b5",3085:"058157d0",3089:"08ba9665",3245:"01afb087",3436:"3a2d9357",3608:"d167c5f4",3699:"3a3d408a",3939:"16fecb72",4013:"3b3dd19c",4510:"8453be59",4608:"f490c5b3",4841:"030bc888",5395:"7d0c359c",5474:"db58d172",5600:"94737017",6103:"07007e46",6401:"a877793b",6680:"e9e08610",6843:"65728b3e",7324:"61cd7b6d",7341:"fe7c9a6a",7407:"923955d7",7414:"e6c104ca",7459:"8f2beab1",7918:"8c705c26",8197:"ca6adc84",8382:"327af9e8",8610:"c5f7b200",9514:"1b29b5d9",9671:"44578da9",9953:"ae256191"}[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)},r={},f="docs-website:",o.l=function(e,t,n,c){if(r[e])r[e].push(t);else{var a,b;if(void 0!==n)for(var d=document.getElementsByTagName("script"),u=0;u=f)&&Object.keys(o.O).every((function(e){return o.O[e](n[b])}))?n.splice(b--,1):(a=!1,f0&&e[u-1][2]>f;u--)e[u]=e[u-1];e[u]=[n,r,f]},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,r){if(1&r&&(e=this(e)),8&r)return e;if("object"==typeof e&&e){if(4&r&&e.__esModule)return e;if(16&r&&"function"==typeof e.then)return e}var f=Object.create(null);o.r(f);var c={};t=t||[null,n({}),n([]),n(n)];for(var a=2&r&&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(f,c),f},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/"+({53:"935f2afb",189:"5647493f",230:"2bc2bb50",570:"31a91795",597:"db1f0725",722:"a6866e6d",1260:"b1e4a2bb",1628:"260cca1a",1719:"4eaee7fa",1782:"460f2046",1944:"99efcd31",1977:"3428807b",2168:"dffbd312",2364:"8c747907",2491:"9fa839ec",2535:"814f3328",2591:"92fe0e90",3015:"eae51d00",3085:"1f391b9e",3089:"a6aa9e1f",3245:"0d4fa94e",3436:"009f1e98",3608:"9e4087bc",3699:"ce7a2be6",3939:"01befa62",4013:"01a85c17",4510:"b8ab82ee",4841:"3fbeb73f",5395:"764f00df",5474:"fc57f22d",5600:"9c504410",6103:"ccc49370",6401:"52275109",6680:"a6235bd5",6843:"e3caf117",7324:"29104dc6",7341:"da250cee",7407:"7bf2db17",7414:"393be207",7918:"17896441",8197:"bb5657b1",8382:"7bc87c9b",8610:"6875c492",9514:"1be78505",9671:"0e384e19",9953:"d4672cd7"}[e]||e)+"."+{53:"47d31997",189:"a947a5ec",230:"cd54028c",570:"503f461d",597:"0cfae94d",722:"31993d98",1260:"b0d3c2b0",1628:"9230c8ff",1719:"b148bac1",1782:"b4f2df60",1944:"e061b5d4",1977:"d8b6adc0",2168:"5b363afd",2364:"9f52e60b",2491:"75f3450c",2535:"936543ce",2591:"080b1dba",3015:"13dd90b5",3085:"058157d0",3089:"08ba9665",3245:"01afb087",3436:"3a2d9357",3608:"d167c5f4",3699:"3a3d408a",3939:"16fecb72",4013:"3b3dd19c",4510:"8453be59",4608:"f490c5b3",4841:"030bc888",5395:"7d0c359c",5474:"db58d172",5600:"94737017",6103:"07007e46",6401:"a877793b",6680:"e9e08610",6843:"65728b3e",7324:"61cd7b6d",7341:"fe7c9a6a",7407:"923955d7",7414:"e6c104ca",7459:"8f2beab1",7918:"8c705c26",8197:"9e963502",8382:"327af9e8",8610:"c5f7b200",9514:"1b29b5d9",9671:"44578da9",9953:"ae256191"}[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)},r={},f="docs-website:",o.l=function(e,t,n,c){if(r[e])r[e].push(t);else{var a,b;if(void 0!==n)for(var d=document.getElementsByTagName("script"),u=0;u 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 da6a660..73a3cae 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 2fd388a..5ac7b9e 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 58ec966..398787e 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 e11a3b1..c00b65d 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 1cd768e..6ea10bc 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 6321676..3218d9e 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 2bc4d38..71f3da5 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 4b545ef..837c4ec 100644 --- a/getting-started/using-predicates.html +++ b/getting-started/using-predicates.html @@ -6,14 +6,14 @@ Using Predicates | Ransack documentation - +

Using Predicates

The primary method of searching in Ransack is by using what is known as predicates.

Predicates are used within Ransack search queries to determine what information to match. For instance, the cont predicate will check to see if an attribute called -"first_name" contains a value using a wildcard query:

>> User.ransack(first_name_cont: 'Rya').result.to_sql
=> SELECT "users".* FROM "users" WHERE ("users"."first_name" LIKE '%Rya%')

You can also combine predicates for OR queries:

>> User.ransack(first_name_or_last_name_cont: 'Rya').result.to_sql
=> SELECT "users".* FROM "users" WHERE ("users"."first_name" LIKE '%Rya%'
OR "users"."last_name" LIKE '%Rya%')

The syntax for OR queries on an associated model is not immediately obvious, but makes sense. Assuming a User has_one Account and the Account has attributes foo and bar:

>> User.ransack(account_foo_or_account_bar: 'val').result.to_sql
=> SELECT "users".* FROM "users" INNER JOIN accounts ON accounts.user_id = users.id WHERE ("accounts.foo LIKE '%val%' OR accounts.bar LIKE '%val%')

Below is a list of the built-in predicates of Ransack and their opposites. You may already +"first_name" contains a value using a wildcard query:

>> User.ransack(first_name_cont: 'Rya').result.to_sql
=> SELECT "users".* FROM "users" WHERE ("users"."first_name" LIKE '%Rya%')

You can also combine predicates for OR queries:

>> User.ransack(first_name_or_last_name_cont: 'Rya').result.to_sql
=> SELECT "users".* FROM "users" WHERE ("users"."first_name" LIKE '%Rya%'
OR "users"."last_name" LIKE '%Rya%')

The syntax for OR queries on an associated model is not immediately obvious, but makes sense. Assuming a User has_one Account and the Account has attributes foo and bar:

>> User.ransack(account_foo_or_account_bar_cont: 'val').result.to_sql
=> SELECT "users".* FROM "users" INNER JOIN accounts ON accounts.user_id = users.id WHERE ("accounts.foo LIKE '%val%' OR accounts.bar LIKE '%val%')

Below is a list of the built-in predicates of Ransack and their opposites. You may already be familiar with some of the predicates, as they also exist in the ARel library.

If you want to add your own, please see the [[Custom-Predicates|Custom Predicates]] page.

Please note: any attempt to use a predicate for an attribute that does not exist will silently fail. For instance, this will not work when there is no name attribute:

>> User.ransack(name_cont: 'Rya').result.to_sql
=> "SELECT "users".* FROM "users"

eq (equals)

The eq predicate returns all records where a field is exactly equal to a given value:

>> User.ransack(first_name_eq: 'Ryan').result.to_sql
=> SELECT "users".* FROM "users" WHERE "users"."first_name" = 'Ryan'

Opposite: not_eq

matches

The matches predicate returns all records where a field is like a given value:

>> User.ransack(first_name_matches: 'Ryan').result.to_sql
=> SELECT "users".* FROM "users" WHERE ("users"."first_name" LIKE 'Ryan')

On Postgres, the case-insensitive ILIKE will be used.

Opposite: does_not_match

Note: If you want to do wildcard matching, you may be looking for the cont/not_cont @@ -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/acts-as-taggable-on.html b/going-further/acts-as-taggable-on.html index e80e9de..335d8cb 100644 --- a/going-further/acts-as-taggable-on.html +++ b/going-further/acts-as-taggable-on.html @@ -6,14 +6,14 @@ Acts-as-taggable-on | Ransack documentation - +

Acts-as-taggable-on

Using Acts As Taggable On

If you have an ActiveRecord model and you're using acts-as-taggable-on, chances are you might want to search on tagged fields. Follow the instructions to install the gem and then set up your project files.

Configure the model

app/models/tasks.rb

You can call the tagging field anything you like, it just needs to be plural. No migration is needed as this is stored in the internal ActsAsTaggable tables (tags and taggings).

class Task < ApplicationRecord
acts_as_taggable_on :projects
end

Controller

Add a field to strong params in the controller. Use the singular name with _list.

app/controllers/tasks_controller.rb

def strong_params
params
.require(:tasks)
.permit(:task, :example_field, :project_list)

Form

We need to send the tag fieldname to our model, also using the singular naming.

<div class='form-group'>
<%= f.label :project_list %>
<%= f.text_field :project_list, value: @task.send(:project_list).to_s %>
</div>

Now we can collect our data via the form, with tags separated by commas.

Imagine you have the following two instances of Task:

{ id: 1, name: 'Clean up my room',        projects: [ 'Home', 'Personal' ] }
{ id: 2, name: 'Complete math exercises', projects: [ 'Homework', 'Study' ] }

When you're writing a Ransack search form, you can choose any of the following options:

<%= search_form_for @search do |f| %>
<%= f.text_field :projects_name_in %> <!-- option a -->
<%= f.text_field :projects_name_eq %> <!-- option b -->
<%= f.text_field :projects_name_cont %> <!-- option c -->
<% end %>

Option A - Match keys exactly

Option a will match keys exactly. This is the solution to choose if you want to distinguish 'Home' from 'Homework': searching for 'Home' will return just the Task with id 1. It also allows searching for more than one tag at once (comma separated):

  • Home, Personal will return task 1
  • Home, Homework will return task 1 and 2

Option B - match key combinations

Option b will match all keys exactly. This is the solution if you wanna search for specific combinations of tags:

  • Home will return nothing, as there is no Task with just the Home tag
  • Home, Personal will return task 1

Option C - match substrings

Option c is used to match substrings. This is useful when you don't care for the exact tag, but only for part of it:

  • Home will return task 1 and 2 (/Home/ matches both "Home" and "Homework")

Option D - select from a list of tags

In Option D we allow the user to select a list of valid tags and then search againt them. We use the plural name here.

<div class='form-group'>
<%= f.label :projects_name, 'Project' %>
<%= f.select :projects_name_in, ActsAsTaggableOn::Tag.distinct.order(:name).pluck(:name) %>
</div>

Multitenancy

ActsAsTaggableOn allows scoping of tags based on another field on the model. Suppose we have a language field on the model, as an effective second level key. We would adjust our model to look like this:

class Task < ApplicationRecord
acts_as_taggable_on :projects
acts_as_taggable_tenant :language
end

The Ransack search is then filtered using the for_tenant method

<div class='form-group'>
<%= f.label :projects_name, 'Project' %>
<%= f.select :projects_name_in, ActsAsTaggableOn::Tag.for_tenant('fr').distinct.order(:name).pluck(:name) %>
</div>
- + \ No newline at end of file diff --git a/going-further/associations.html b/going-further/associations.html index a19f6b2..e4280e2 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 31f4c53..c626ee3 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 c0899a2..9003625 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

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 14f7f66..54c0a11 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 75c1458..262fd46 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 28884fc..613a54e 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 b9041d5..c7fb4cf 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 7251c14..37e52cf 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 issue 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 2a3a416..cdde011 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/polymorphic-search.html b/going-further/polymorphic-search.html index af3ebcb..96aa6c5 100644 --- a/going-further/polymorphic-search.html +++ b/going-further/polymorphic-search.html @@ -6,13 +6,13 @@ Polymorphic Searches | Ransack documentation - +

Polymorphic Searches

When making searches from polymorphic models it is necessary to specify the type of model you are searching.

For example:

Given two models

class House < ActiveRecord::Base
has_one :location, as: :locatable
end

class Location < ActiveRecord::Base
belongs_to :locatable, polymorphic: true
end

Normally (without polymorphic relationship) you would be able to search as per below:

Location.ransack(locatable_number_eq: 100).result

However when this is searched you will get the following error

ActiveRecord::EagerLoadPolymorphicError: Can not eagerly load the polymorphic association :locatable

In order to search for locations by house number when the relationship is polymorphic you have to specify the type of records you will be searching and construct your search as below:

Location.ransack(locatable_of_House_type_number_eq: 100).result

note the _of_House_type_ added to the search key. This allows Ransack to correctly specify the table names in SQL join queries.

- + \ No newline at end of file diff --git a/going-further/ransackers.html b/going-further/ransackers.html index 665c576..7688eb7 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 a3bd759..33c412a 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 9ca5f6c..c368d94 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 5a501e4..1e5294f 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/going-further/wiki-contributors.html b/going-further/wiki-contributors.html index eb754fe..959f501 100644 --- a/going-further/wiki-contributors.html +++ b/going-further/wiki-contributors.html @@ -6,13 +6,13 @@ Wiki Contributors | Ransack documentation - +

Wiki Contributors

Ransack previously had documentation contained in a GitHub Wiki, and this content has been merged into this documentation website. The following long list of amazing people all made contributions to the Wiki:

  • Abinoam P. Marques Jr
  • Alex Stophel
  • Andrea Schiavini
  • Andrew Vit
  • Ben Koshy
  • Brainkurv
  • Brandan Lennox
  • Brendon Muir
  • Chris Salzberg
  • Colleen McGuckin
  • David Aldridge
  • Davidson Mohanty
  • Denis Tataurov
  • Drew Moore
  • Eike Send
  • Feodor Cherashev
  • Glauco Custódio
  • Grey Baker
  • Harold.Luo
  • Herman Singh
  • Ian Smith
  • Jake Haber
  • Jan Klimo
  • Jared Beck
  • Jon Atack
  • Juanito Fatas
  • JungaJk
  • Leo Chen
  • Leon Miller-Out
  • Luca F
  • Marc Poris
  • Matt Oakley
  • Michael Kopchick
  • Nathan Colgate
  • Nguyen Phi Viet(Sun*)
  • Nguyễn Đức Long
  • NielsKSchjoedt
  • Patrick Copeland
  • Pedro Chambino
  • Rene Hopf
  • Richa Arora
  • Rob Jones
  • Roman Sokhan
  • Ryan Bates
  • Ryan Bigg
  • Sean
  • Sean Linsley
  • Sergey
  • Sunny Ripert
  • Tanbir Hasan
  • ThuyNguyen97
  • Vanda
  • Yana Agun Siswanto
  • bonyiii
  • charly
  • chifung7
  • colorfulberry
  • ddonahue99
  • ernie
  • gaaady
  • gingerlime
  • grumpit
  • itsalongstory
  • jonatack
  • kogre
  • nguyentrungson97
  • nslocum
  • omitter
  • radar
  • rilian
  • terraplane
  • tyronewilson
  • vansy61
  • willnet
  • wzcolon
- + \ No newline at end of file diff --git a/index.html b/index.html index 2369540..0db5125 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 7f37d71..cd23c8b 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