Ecto schema belongs_to association using two fields

Viewed 265

I have two models: Auction and Artwork. An Artwork belongs_to an Auction.

This is set-up against an external db, so the migrations are not handled by Ecto and the fields are camelcased in the underlying db.

The issue I am running into is that the association is done via two fields (a tuple association): token_id and contract_address.

Neither token_id nor contract_address are unique, however as a tuple they are unique.

This is the Auction schema:

@primary_key {:auction_id, :id, source: :auctionId}
schema "auction" do
  field :token_id, :integer, source: :tokenId
  field :contract_address, :string, source: :contractAddress
  
  # ideally would want to do something like this
  belongs_to :artwork, Foundation.Artworks.Artwork,
    references: [:contract_address, :token_id]

end

And then the Artwork schema:

@primary_key {:id, :binary_id, []}
schema "artwork" do
  field :name, :string
  field :description, :string
  field :token_id, :integer, source: :tokenId
  field :contract_address, :string, source: :contractAddress
end

How could I approach this so that the Artwork is associated using both fields?

1 Answers

Does it works for you:

@primary_key false
schema "artwork" do
  field :name, :string
  field :description, :string
  field :token_id, :integer, source: :tokenId, primary_key: true
  field :contract_address, :string, source: :contractAddress, primary_key: true
end
Related