Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add guide on how to scope has_many relations #2243

Merged
merged 1 commit into from
Aug 11, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 3 additions & 2 deletions docs/guides.md
Original file line number Diff line number Diff line change
Expand Up @@ -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)
27 changes: 27 additions & 0 deletions docs/guides/scoping_has_many_relations.md
Original file line number Diff line number Diff line change
@@ -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')
```