# Making instance dependant :has\_many scope optional

**URL:** <https://discuss.rubyonrails.org/t/making-instance-dependant-has-many-scope-optional/77681>\
**Category:** rubyonrails-talk\
**Tags:** activerecord\
**Created:** [April 27, 2021, 9:10pm UTC](https://discuss.rubyonrails.org/t/making-instance-dependant-has-many-scope-optional/77681 "2021-04-27T21:10:53Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![chautelly](https://sea2.discourse-cdn.com/rubyonrails/user_avatar/discuss.rubyonrails.org/chautelly/32/2786_2.png) [@chautelly](https://discuss.rubyonrails.org/u/chautelly)\
**Post date:** [April 27, 2021, 9:10pm UTC](https://discuss.rubyonrails.org/t/making-instance-dependant-has-many-scope-optional/77681/1 "2021-04-27T21:10:54Z")

</div>

I was looking to add an instance dependant scope to a model’s attribute `has_many` configuration:

```ruby
has_many :sandwiches, -> (user) { where(account_id: user.account_id) }

```

Unfortunately, this breaks existing usage of of the attribute nested in `.includes` calls.

Is it possible to define the scope optionally? As in, if an instance is available, use the scope but ignore it if not?

---

<div class="post-metadata">

**Author:** ![chautelly](https://sea2.discourse-cdn.com/rubyonrails/user_avatar/discuss.rubyonrails.org/chautelly/32/2786_2.png) [@chautelly](https://discuss.rubyonrails.org/u/chautelly)\
**Post date:** [May 6, 2021, 2:05pm UTC](https://discuss.rubyonrails.org/t/making-instance-dependant-has-many-scope-optional/77681/2 "2021-05-06T14:05:21Z")

</div>

I’ve resolved this by adding an alternative association:

```ruby
has_many :sandwiches
has_many :sandwiches_alt, -> (user) { where(account_id: user.account_id) }

```

and adding a overriding getter method so that instances of the model will use the alternative while the origianl association can still be used wherever `.includes` is used.

```ruby
...
def sandwiches
  sandwiches_alt
end

```
