Skip to content

Non-standard id via primary_key option on Belongs To field not respected #3413

Closed
@therabidbanana

Description

@therabidbanana

Describe the bug

We have a table that has an integer id (deprecated) and a uuid used for all new tables. This is easy to define in the activerecord relationship via primary_key:

belongs_to :user, primary_key: :uuid

But the Avo belongs to field for this relationship still tries to save using the #id method. Depending on if the id field exists on the table this will either generate a NoMethodError or, in our case since we actually have both, using an invalid integer type id, silently failing.

Steps to Reproduce

Steps to reproduce the behavior:

  1. Add uuid identifier column to existing table with integer ids. Define relationship using this new column.
  2. Configure a field :user, as: :belongs_to
  3. Try to edit the newly added field via Avo

Expected behavior & Actual behavior

Observe id param is sent rather than uuid

Models and resource files

# == Schema Information
#
# Table name: posts
#
#  id                :uuid             not null, primary key
#  title             :string
# user_id :uuid
#
# Indexes
#
#  index_posts_on_user_id  (user_id)
#
class Post
  belongs_to :user, primary_key: :uuid, optional: true
end
# == Schema Information
#
# Table name: users
#
#  id                     :bigint(8)        not null, primary key
#  name                   :string           not null
#  uuid                   :uuid             not null
#
# Indexes
#
#  index_users_on_uuid                  (uuid) UNIQUE
class User
end
class Avo::Resources::Post
  def fields
    field :title, as: :text
    field :user, as: :belongs_to
  end
end

System configuration

Avo version:
= 3.13.7

Rails version:
= 7.2.1.2

Ruby version:

License type:

  • Community
  • Pro
  • Advanced

Additional context

My best guess following code path is that it looks like id is assumed to the the primary key here, but reflections should be used like they are for the foreign key option:

https://github.com/avo-hq/avo/blob/main/lib/avo/fields/belongs_to_field.rb#L219

Impact

  • High impact (It makes my app un-usable.)
  • Medium impact (I'm annoyed, but I'll live.)
  • Low impact (It's really a tiny thing that I could live with.)

Urgency

  • High urgency (I can't continue development without it.)
  • Medium urgency (I found a workaround, but I'd love to have it fixed.)
  • Low urgency (It can wait. I just wanted you to know about it.)

Metadata

Metadata

Assignees

No one assigned

    Labels

    BugSomething isn't working

    Type

    No type

    Projects

    Status

    Done

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions