From f288a7348e6c194aec9c6a2e8c83b3212dd08185 Mon Sep 17 00:00:00 2001 From: Jose Varela Date: Wed, 10 Aug 2022 00:13:40 -0500 Subject: [PATCH] Add guide on how to scope has_many relations --- docs/guides.md | 5 +++-- docs/guides/scoping_has_many_relations.md | 27 +++++++++++++++++++++++ 2 files changed, 30 insertions(+), 2 deletions(-) create mode 100644 docs/guides/scoping_has_many_relations.md diff --git a/docs/guides.md b/docs/guides.md index 4718e97079..66e2f2bdfb 100644 --- a/docs/guides.md +++ b/docs/guides.md @@ -2,5 +2,6 @@ title: Guides --- -* [Hiding Dashboards from the Sidebar](./guides/hiding_dashboards_from_sidebar) -* [Customising the search](./guides/customising_search) +- [Hiding Dashboards from the Sidebar](./guides/hiding_dashboards_from_sidebar) +- [Customising the search](./guides/customising_search) +- [Scoping HasMany Relations](./guides/scoping_has_many_relations.md) diff --git a/docs/guides/scoping_has_many_relations.md b/docs/guides/scoping_has_many_relations.md new file mode 100644 index 0000000000..65bf3944cb --- /dev/null +++ b/docs/guides/scoping_has_many_relations.md @@ -0,0 +1,27 @@ +--- +title: Scoping HasMany Relations +--- + +To show a subset of a has_many relationship, create a new [has_many](https://apidock.com/rails/ActiveRecord/Associations/ClassMethods/has_many) relationship in your model (using the `scope` argument) and add it to the model's dashboard. + +## Creating a scoped has_many relationship + +Models can define subsets of a `has_many` relationship by passing a callable (i.e. proc or lambda) as its second argument. + +```ruby +class Customer < ApplicationRecord + has_many :orders + has_many :processed_orders, ->{ where(processed: true) }, class_name: "Order" +``` + +Since ActiveRecord infers the class name from the first argument, the new `has_many` relation needs to specify the model using the `class_name` option. + +## Add new relationship to dashboard + +Your new scoped relation can be used in the dashboard just like the original `HasMany`. Notice the new field needs to specifiy the class name as an option like you did in the model. + +```ruby +ATTRIBUTE_TYPES = { + orders: Field::HasMany, + processed_orders: Field::HasMany.with_options(class_name: 'Order') +```