Avoiding extra queries in belongs_to relationship management

I have an update action on an Ash resource that manages a belongs_to relationship:

    change manage_relationship(:business, type: :append_and_remove)

I’ve noticed that when the attributes and relationship arguments passed in to the update action result in no change - no SQL update - multiple SQL select queries run anyway to check the relationships.

How might I side-step the relationship management when the foreign key is not changing, so that the relationship management queries are skipped?

Hm…seems like maybe something that it should be doing by default. But in terms of how you can do it yourself, your best bet would be switching to a custom change, like:

change fn changeset, _ -> 
  new_business_id = changeset.arguments[:business_id]
  if new_business_id && new_business_id != changeset.data.business_id do
    Ash.Changeset.manage_relationship(changeset, :business, ....)
  else
    changeset
  end
end
1 Like