https://avo.cool logo
Linked belongs_to fields + attach_scope
# avo-2
b
My
ClientResource
has two
belongs_to
fields—`hospital` and `hospital_contact`—that are linked. That is, when a user is editing a
Client
and selects a
hospital
, the
hospital_contact
select should only show contacts associated with that hospital. I've gotten part of the way there using
attach_scope
, like so:
Copy code
ruby
field :hospital_contact,
  as: :belongs_to,
  attach_scope: -> { query.active.from_hospital(parent.hospital_id) },
  required: false
This works when editing an existing
Client
, but falls over when the
hospital
is updated (but not saved) or when creating a new
Client
, because it's reading the
hospital_id
from the
parent
rather than getting it from the previous field. Is there a way to modify the field's
attach_scope
based on the previous field's value? (I think if this were a
select
and not a
belongs_to
, I could do it with computed options?)
l
Hello @better-restaurant-41251 I would use a select field on the
hospital_contact
and connect that field to a stimulus controller that react on
hospital
change, fetching the values from a custom endpoint (passing the
hospital
PK as param) and repopulate the select on each change. Let me know if you need some help, we have an example on our demo app on the courses form with the countries and cities https://main.avodemo.com/avo/resources/courses/new
l
another way to do it is to add some stimulus JS magic there
please check this guide
this does basically that. when a user changes the country, we fetch the cities and update the
cities
select field