From 0c41e46b58aaed6867b655b275e17535b879d91d Mon Sep 17 00:00:00 2001 From: jbranchaud Date: Thu, 18 Mar 2021 21:28:09 -0500 Subject: [PATCH] Add Link To The Current Page With Query Params as a Rails til --- README.md | 3 +- ...k-to-the-current-page-with-query-params.md | 36 +++++++++++++++++++ 2 files changed, 38 insertions(+), 1 deletion(-) create mode 100644 rails/link-to-the-current-page-with-query-params.md diff --git a/README.md b/README.md index ea8de20..1246b69 100644 --- a/README.md +++ b/README.md @@ -10,7 +10,7 @@ pairing with smart people at Hashrocket. For a steady stream of TILs, [sign up for my newsletter](https://tinyletter.com/jbranchaud). -_1090 TILs and counting..._ +_1091 TILs and counting..._ --- @@ -678,6 +678,7 @@ _1090 TILs and counting..._ - [Ignore Poltergeist JavaScript Errors](rails/ignore-poltergeist-javascript-errors.md) - [Include Devise Helpers In Your Controller Tests](rails/include-devise-helpers-in-your-controller-tests.md) - [Inspect Previous Changes To ActiveRecord Object](rails/inspect-previous-changes-to-activerecord-object.md) +- [Link To The Current Page With Query Params](rails/link-to-the-current-page-with-query-params.md) - [List All Installable Rails Versions](rails/list-all-installable-rails-versions.md) - [List The Enqueued Jobs](rails/list-the-enqueued-jobs.md) - [Load Records In Batches With find_each](rails/load-records-in-batches-with-find-each.md) diff --git a/rails/link-to-the-current-page-with-query-params.md b/rails/link-to-the-current-page-with-query-params.md new file mode 100644 index 0000000..e39fc53 --- /dev/null +++ b/rails/link-to-the-current-page-with-query-params.md @@ -0,0 +1,36 @@ +# Link To The Current Page With Query Params + +The `link_to` method is an ActionView helper for generating an `a` tag within a +Rails view. There are two arguments that tend to comprise this method: the link +text and a path helper. + +```ruby +<%= link_to 'Home', root_path %> +``` + +The `link_to` method can be used to generate a link to the current page with +query params. You can do this be providing a hash instead of a path helper as +the second argument. + +```ruby +<%= link_to "All", {filter: 'all'} %> +<%= link_to "New", {filter: 'new'} %> +<%= link_to "Posted", {filter: 'posted'} %> +``` + +The hash can contain one or more key-value pairs which will be turned into +query params and appended to the end of the current base path. + +If these are part of the `posts` index page, then they will render as: + +```html +All +New +Posted +``` + +This is a great way to create links for a Rails action that presents different +data based on query params. Often this is an index page where filtering is +needed. + +[source](https://gorails.com/episodes/rails-link-to-current-page-with-params)