typeid-elixir
typeid-elixir copied to clipboard
Possible belongs_to improvement
I just started to work with adding TypeIDs to my app and immediately ran into issues with belongs_to
. I've looked at the other issues and I did get it to work by using define_field: false
and a separate field :thing_id
. It did however feel like it should work to just do
schema "posts" do
has_many :comments, Comment
end
schema "comments" do
belongs_to :post, Post, type: TypeID
end
but when I tried that I got an error about type
was only allowed to be :uuid
or :string
. Without using type: TypeID
I got an error about value #TypeID<"aaa_01j95zhepsf75rfymj6egjqg9m"> in where cannot be cast to type :integer in query
.
Digging further I realized that when using type
param to belongs_to
, the value for type
is included in the call to TypeID.init
. This means when using type: TypeID
, dump
will try to see what database type it should convert itself to, but the type is TypeID
, which is the Ecto custom type, not the database type.
I have a solution to this which changes the name of the type
parameter to column_type
, so the primary key definitions become
@primary_key {:id, TypeID, autogenerate: true, prefix: "post", column_type: :uuid}
and the belongs_to definitions becomes
belongs_to :wallet, Wallet, type: TypeID, column_type: :uuid
With a default of :uuid, the column_type
can also be dropped.
I'm guessing this is something around the differences of how Ecto handles a ParameterizedType
when used as a normal field and an association. Would you be interested in a PR for this if I clean it up? Or am I missing something here that makes it a bad idea?